<?php

namespace App\Core\Service;

use App\Core\Repository\PropertyFactMapping\PropertyFactMappingRepository;
use App\Core\Service\LanguageService ;
use App\Core\Service\ApplicationCacheService ;
use App\Core\Validator\PropertyFact\PropertyFactCheckboxValidator;

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

class PropertyFactMappingService
{

    private $languageService;
    private $propertyFactMappingRepository;
    private $applicationCacheService ;
    private $propertyFactCheckboxValidator ;


    public function __construct(
        PropertyFactMappingRepository $propertyFactMappingRepository,
        LanguageService $languageService,
        ApplicationCacheService $applicationCacheService,
        PropertyFactCheckboxValidator $propertyFactCheckboxValidator

    )
    {
        $this->languageService = $languageService;
        $this->propertyFactMappingRepository = $propertyFactMappingRepository;
        $this->applicationCacheService = $applicationCacheService;
        $this->propertyFactCheckboxValidator = $propertyFactCheckboxValidator;

    }

    public function create($param = [])
    {
        $response = ['status' => -1, 'message' => '', 'data' => null];
        try {
            $insertData =
                [

                    "status" => fillOnUndefined($param, "status", 0),
                    "created_by" => fillOnUndefined($param, "created_by"),
                    "updated_by" => fillOnUndefined($param, "updated_by"),
                    "created_at" => time(),
                    "updated_at" => time(),
                ];


            $userCreateResult = $this->propertyFactMappingRepository->create($insertData);
            if ($userCreateResult['status'] != 'success') {
                throw new Exception('api-unknown_error');
            }
            $userData = $userCreateResult["data"]->toArray();

            $response['status'] = 1;
            $response['data'] = $userData;


        } catch (ApiErrorException $e) {
            $response['status'] = 0;
            $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 select($param = [], $column = ['*'])
    {

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

        try {

            $data = $this->propertyFactMappingRepository->findByCriteria($param, $column);
            $response = [
                'status' => true,
                'data' => $data,
            ];

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

        return output($response);
    }

    public function deleteById($param){

        $userCreateResult = $this->propertyFactMappingRepository->delete();

    }

    public function removePropertyFactMapping($param = [])
    {

    //Todo: validations

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


            //Todo: cache datası yeni bir fonksiyon yapılıp herkes oradan geçekecek

            $cacheInfo = $this->applicationCacheService->getApplicationCache([]);
            if($cacheInfo['status'] != 'success'){
                throw new ApiErrorException(lang('Cache Required'));
            }
            $userData = $cacheInfo['data'] ;


            $factIds = [];
            foreach ($param["facts"] as $fact){
                $factIds[] = $fact["id"];
            }


            $findCriteria = [
                'criteria' => [
                    ['field' => 'property_id', 'condition' => '=', 'value' => $userData['property_id']],
                ],
                "whereIn"=>
                    [
                        ["field"=>"fact_id","value"=>$factIds]
                    ]
            ];

            $factMappingDatas = $this->propertyFactMappingRepository->findByCriteria($findCriteria);
            if (!$factMappingDatas) {
                throw new ApiErrorException(lang('Fact cannot loaded'));
            }


            // Todo: gönderilen idler ile veritabanında bulunan idler karşılaştırılacak. Uyumsuz data varsa hiç bir şey silinmeden error throw edilecek

            $deleteRowIds = [];
            foreach ($factMappingDatas as $factMappingData){
                $ids = [];
                $ids[] = $factMappingData["id"];
                $delete = $this->propertyFactMappingRepository->deleteById($ids);
                if (!$delete) {
                    throw new ApiErrorException(lang('cannot delete fact'));
                }

            }
            $response['status'] = 1;
            $response['data'] = [];



            }
            catch (ApiErrorException $e) {
                $response['status'] = 0;
                $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 addPropertyFactMapping($params = [])
    {
        $response = ['status' => -1, 'message' => '', 'data' => null];
        try
        {
            $propertyId       = $params['property_id'];
            $userId           = $params['user_id'];
            $propertyFactData = $params['data'];

            $addPropertyFactMapping = [];
            foreach ($propertyFactData as $key => $param)
            {
                $addPropertyFactMapping[] =
                    [
                        'property_id' => $propertyId,
                        'fact_id' => fillOnUndefined($param, 'id'),
                        'created_by' => $userId,
                        'updated_by' => $userId,
                    ];
            }

            //TODO : $addPropertyFactMapping için validation işlemleri yapılacaktır.(property_id ve fact id inin unique doğrulamasına bakılması unutulmamalı )
            $response = $this->propertyFactMappingRepository->createAll($addPropertyFactMapping);

            if ($response['status'] != 'success') {
                throw new Exception('api-unknown_error');
            }

            $response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => null];

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

        return output($response);
    }

    public function updatePropertyFactMapping($params = [])
    {
        $response = ['status' => -1, 'message' => '', 'data' => null];
        try
        {

            $validationResult = $this->propertyFactCheckboxValidator->validate($params);

            if ($validationResult->errors()->first()) {
                $errors = $validationResult->errors()->all();
                throw new ApiErrorException($errors);
            }

            $addPropertyFactMapping = [];
            $addFactList = collect($params['property_fact'])
                ->where('is_selected' ,'=', true);
            $addFactIds = $addFactList->keyBy("id")->keys()->toArray();

            $removeFactList = collect($params['property_fact'])
                ->where('is_selected' ,'=', false);

            $removeFactIds = $removeFactList->keyBy("id")->keys()->toArray();

            $checkPropertyMappingRequest = [
                'criteria' => [
                    ['field' => 'property_id', 'condition' => '=', 'value' => $params['property_id']],
                ],
                "whereIn" => [
                    ["field" => "fact_id", "value" => $addFactIds]
                ]
            ];
            $checkPropertyMappingResponse = $this->select($checkPropertyMappingRequest,['id', 'property_id', 'fact_id']);

            if($checkPropertyMappingResponse['status'] != 'success'){
                throw new ApiErrorException(lang('Mapping data not loaded'));
            }
            $checkPropertyMappingCollect = collect($checkPropertyMappingResponse['data']);

            foreach ($addFactList->toArray() as $key => $param)
            {

                $isFactMappingBefore = $checkPropertyMappingCollect->where('property_id', '=', $params['property_id'])
                    ->where('fact_id', '=', $param['id'])
                    ->first();

                $description = [] ;
                foreach (fillOnUndefined($param, "description", []) as $title) {
                    $description[$title['language_code']] = !empty($title['description']) ? $title['description'] : null;
                }

                if(empty($isFactMappingBefore)){

                    $addPropertyFactMapping[] =
                        [
                            'property_id' => $params['property_id'],
                            'fact_id' => fillOnUndefined($param, 'id'),
                            'description' => !empty($description) ? json_encode($description) : null,
                            'created_by' => $params['user_id'],
                            'updated_by' => $params['user_id'],
                        ];

                } else {
                    $this->propertyFactMappingRepository->update($isFactMappingBefore['id'], ['description' => !empty($description) ? json_encode($description) : null]);
                }
            }

            $response = $this->propertyFactMappingRepository->createAll($addPropertyFactMapping);


            if($removeFactIds){

                $findCriteria = [
                    'criteria' => [
                        ['field' => 'property_id', 'condition' => '=', 'value' => $params['property_id']],
                    ],
                    "whereIn" =>
                        [
                            ["field" => "fact_id", "value" => $removeFactIds]
                        ]
                ];

                $deletePropertyFactMapping = $this->propertyFactMappingRepository->findByCriteria($findCriteria);

                $deleteThisIds = [];
                foreach ($deletePropertyFactMapping as $deleteThisItem){
                    $deleteThisIds[] = $deleteThisItem['id'];
                }

                if($deleteThisIds){
                    $this->propertyFactMappingRepository->deleteById($deleteThisIds);

                }
            }

            if ($response['status'] != 'success') {
                throw new ApiErrorException(lang('Data is not added')) ;
            }

            $response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => null];

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

        return output($response);
    }

    }
