<?php

namespace App\Libs\Backoffice\Generic\Fields;

use App\Libs\Contracts\Backoffice\DuplicatableField;
use App\Libs\Contracts\Backoffice\SavableField;
use App\Libs\Contracts\Backoffice\VersionableField;
use App\Libs\Facades\RequestContext;

class LocationField extends BaseField implements SavableField, VersionableField, DuplicatableField
{

    protected $required = false;

    public function __construct($config)
    {
        unset($config["multiLanguage"]);
        unset($config["validation"]);
        unset($config["preValidation"]);
        unset($config["inList"]);
        unset($config["search"]);
        unset($config["sort"]);

        parent::__construct($config);

        if (!empty($config["required"])) {
            $this->required = $config["required"];
        }
    }

    public function isRequired()
    {
        return $this->required;
    }

    public function setRequired($required)
    {
        $this->required = $required;
    }

    public function getLatName()
    {
        return $this->getName()."_lat";
    }

    public function getLngName()
    {
        return $this->getName()."_lng";
    }

    public function getZoomName()
    {
        return $this->getName()."_zoom";
    }

    public function getCurrentValue($model)
    {
        $fieldName = $this->getName();

        $value = array("lat" => null, "lng" => null, "zoom" => 1);

        $latName = $this->getLatName();
        $lngName = $this->getLngName();
        $zoomName = $this->getZoomName();

        if (request()->has($latName)) {
            $value["lat"] = request()->input($latName);
        } elseif ($model->exists) {
            $value["lat"] = $model->$latName;
        }

        if (request()->has($lngName)) {
            $value["lng"] = request()->input($lngName);
        } elseif ($model->exists) {
            $value["lng"] = $model->$lngName;
        }

        if (request()->has($zoomName)) {
            $value["zoom"] = request()->input($zoomName);
        } elseif ($model->exists) {
            $value["zoom"] = $model->$zoomName;
        }

        return $value;
    }

    public function toForm($model, $enabled = true, $hidden = false)
    {
        $html = "";

        $fieldName = $this->getName();
        $value = array("lat" => null, "lng" => null, "zoom" => 1);

        if ($model->exists) {
            $latName = $this->getLatName();
            $lngName = $this->getLngName();
            $zoomName = $this->getZoomName();
            $value["lat"] = $model->$latName;
            $value["lng"] = $model->$lngName;
            if (!is_null($model->$zoomName)) {
                $value["zoom"] = $model->$zoomName;
            }
        }

        $errors = RequestContext::get("errors");
        $hasErrors = false;
        if (!empty($errors) && !$errors->isEmpty()) {
            if ($errors->has("{$this->getName()}.lat") ||
                $errors->has("{$this->getName()}.lng") ||
                $errors->has("{$this->getName()}.zoom")) {
                $hasErrors = true;
            }
        }


        $html .= view(
            "admin.generic.components.forms.location",
            array(
                "id" => $this->getName(),
                "errorLatKey" => $this->getName().".lat",
                "errorLngKey" => $this->getName().".lng",
                "errorZoomKey" => $this->getName().".zoom",
                "hasErrors" => $hasErrors,
                "name" => $this->getName(),
                "label" => $this->getLabel(),
                "value" => $value,
                "hidden" => $hidden,
                "enabled" => $enabled,
                "required" => $this->isRequired(),
                "parentHidden" => ($hidden && !empty($this->parent)),
                "parent" => $this->parent,
                "info" => $this->getInfo(),
                "blocksMode" => $this->blocksMode,
            ));


        return $html;
    }

    public function save($model, $values)
    {

        $latName = $this->getLatName();
        $lngName = $this->getLngName();
        $zoomName = $this->getZoomName();

        if (empty($values["lat"]) || empty($values["lng"])) {
            $model->$latName = null;
            $model->$lngName = null;
            $model->$zoomName = null;
        } else {
            $model->$latName = $values["lat"];
            $model->$lngName = $values["lng"];
            $model->$zoomName = $values["zoom"];
        }
    }

    public function getValidation($isZoom = false)
    {
        $rules = "";
        if ($this->isRequired()) {
            $rules = "required|";
        }

        if ($isZoom) {
            $rules .= "integer|min:0";
        } else {
            $rules .= "numeric";
        }


        return $rules;
    }

    public function getValidationData($copyAllLang = false)
    {
        $validation = array(
            "rules" => array(),
            "values" => array(),
            "labels" => array()
        );

        $rules = $this->getValidation();
        $fieldName = $this->getName();
        $validation["values"][$fieldName] = request()->input($fieldName);
        $validation["rules"][$fieldName.".lat"] = $this->getValidation();
        $validation["rules"][$fieldName.".lng"] = $this->getValidation();
        $validation["rules"][$fieldName.".zoom"] = $this->getValidation(true);
        $validation["labels"][$fieldName.".lat"] = strtolower(trans("backend.latitude"));
        $validation["labels"][$fieldName.".lng"] = strtolower(trans("backend.longitude"));
        $validation["labels"][$fieldName.".zoom"] = "zoom";

        return $validation;
    }

    public static function getScript()
    {
        $googleKey = config("google.apiKey");
        if (!empty($googleKey)) {
            return array(
                "locationPicker" =>
                    path_asset('path.backoffice.js_path').'/view/backend-location-picker.js',
                "googleMap" => 'https://maps.googleapis.com/maps/api/js?key='.$googleKey
            );
        } else {
            return null;
        }
    }

    public function toArray()
    {
        $array = parent::toArray();
        $array["required"] = $this->required;
        return $array;
    }

    public function getVersionStructure($model)
    {
        $fieldVersion = array();
        $fieldName = $this->getName();

        $fieldVersion['multilanguage'] = false;
        $fieldVersion['value'] = $this->getCurrentValue($model);

        return $fieldVersion;
    }

    public function loadVersion($model, $fields, $langFields)
    {
        $fieldName = $this->getName();
        $latName = $this->getLatName();
        $lngName = $this->getLngName();
        $zoomName = $this->getZoomName();
        if (isset($fields[$fieldName]) && !empty($fields[$fieldName])) {
            $model->$latName = $fields[$fieldName]["lat"];
            $model->$lngName = $fields[$fieldName]["lng"];
            $model->$zoomName = $fields[$fieldName]["zoom"];
        }
    }

    public function duplicate($sourceModel, $model)
    {
        $fieldName = $this->getName();
        $latName = $this->getLatName();
        $lngName = $this->getLngName();
        $zoomName = $this->getZoomName();

        $model->$latName = $sourceModel->$latName;
        $model->$lngName = $sourceModel->$lngName;
        $model->$zoomName = $sourceModel->$zoomName;
    }
}


