<?php


namespace App\Core\Service;

use App\Core\Repository\ApplicationCache\ApplicationCacheRepository;
use App;

use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Config;
use Exception;
use App\Exceptions\ApiErrorException;
use Illuminate\Http\Request;


class ApplicationCacheService
{

    private $applicationCacheRepository;
    private $request ;

    public function __construct(

        ApplicationCacheRepository $applicationCacheRepository,
        Request $request

    )
    {

        $this->applicationCacheRepository = $applicationCacheRepository ;
        $this->request = $request ;
    }

    public  function applicationCacheCreate($params){

        $response = ['status' => -1, 'message' => '', 'data' => null];
        try {
            if(!fillOnUndefined($params, 'token')){
                throw new ApiErrorException(lang('Token Required'));
            }
            $cacheId = md5($params['token']) ;
            unset($params['token']);

            $cacheResult = $this->applicationCacheRepository->storeCache($cacheId, $params);
            $response = [
                'status' => true,
                'data' => $cacheResult,
            ];

        } catch (ApiErrorException $e) {
            $response['message'] = implode(', ', $e->getMessageArr());
        } catch (Exception $e) {
            $message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
            Log::error($message);
            $response['message'] = $e->getMessage();
        }

        return output($response);



    }

    public  function getApplicationCache($params){

        $response = ['status' => -1, 'message' => '', 'data' => null];
        try {

            $token = $this->request->header('authToken');


            if(!$token){
                throw new ApiErrorException(lang('Token Required'));
            }
            $cacheId = md5($token) ;


            $cacheResult = $this->applicationCacheRepository->getCache($cacheId);

            if(!$cacheResult){

                throw new ApiErrorException(lang('Cache Info not found'));
            }

            $response = [
                'status' => true,
                'data' => $cacheResult,
            ];

        } catch (ApiErrorException $e) {
            $response['message'] = implode(', ', $e->getMessageArr());
        } catch (Exception $e) {
            $message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
            Log::error($message);
            $response['message'] = $e->getMessage();
        }

        return output($response);



    }
}