<?php

namespace ThurData\Servers\KerioEmail\App\UI\Client\Ressource\Providers;

use ThurData\Servers\KerioEmail\App\Enums\Kerio;
use function ThurData\Servers\KerioEmail\Core\Helper\di;
use ThurData\Servers\KerioEmail\Core\UI\ResponseTemplates\HtmlDataJsonResponse;
use ThurData\Servers\KerioEmail\Core\UI\Widget\Forms\DataProviders\BaseDataProvider;
use ThurData\Servers\KerioEmail\Api\KerioWhmcs;

/**
 *
 * Created by PhpStorm.
 * User: ThurData
 * Date: 18.09.19
 * Time: 09:35
 * Class EditRessourceDataProvider
 */
class EditRessourceDataProvider extends BaseDataProvider
{

    /**
     *
     */
    public function read()
    {
        $fields = array(
            "id",
            "name",
            "description",
            "type",
            "isEnabled",
            "manager"
        );
        $cond = array(
                "fieldName" => "id",
                "comparator" => "Eq",
                "value" => $this->actionElementId
        );

        $api = new KerioWhmcs('whmcsKerioEmail', 'Thurdata', '1.0');
        try {
            $api->login($this->getWhmcsParamByKey('serverhostname'), $this->getWhmcsParamByKey('serverusername'), $this->getWhmcsParamByKey('serverpassword'));
            $domainID = $api->getDomainId($this->getWhmcsParamByKey('domain'));
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }
        try {
            $ressource = $api->getResources($fields,$domainID,[ $cond ]);
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }
        $attr = array(
            "id",
            "loginName",
            "isEnabled");
        try {
            $users = $api->getUsers($attr,$domainID);
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }
        $api->logout();
        $this->availableValues['manager'][$ressource[0]['manager']['id']] = $ressource[0]['manager']['name'] . '@' . $ressource[0]['manager']['domainName'];
        foreach($users as $user) {
            if($user['isEnabled']){
                $this->availableValues['manager'][ $user['id']] = $user['loginName'] . '@' . $this->getWhmcsParamByKey('domain');
            }
        }

        $lang = di('lang');
        $this->data['id']            = $ressource[0]['id'];
        $this->data['name']          = $ressource[0]['name'];
        $this->data['domain']        = $this->getWhmcsParamByKey('domain');
        $this->data['status']        = $ressource[0]['isEnabled'] == true ? Kerio::ACC_STATUS_ACTIVE : Kerio::ACC_STATUS_CLOSED;
        $this->data['type']          = $ressource[0]['type'] === 'Room' ? Kerio::RES_TYPE_LOCATION : Kerio::RES_TYPE_EQUIPMENT;
        $this->data['description']   = $ressource[0]['description'];
        $this->data['manager']       = $ressource[0]['manager']['name'] . '@' . $ressource[0]['manager']['domainName'];

        $this->availableValues['status'] = [
            Kerio::ACC_STATUS_ACTIVE        => $lang->absoluteT('kerio','account','status','active'),
            Kerio::ACC_STATUS_CLOSED        => $lang->absoluteT('kerio','account','status','closed'),
        ];

        $this->availableValues['type'] = [
            Kerio::RES_TYPE_LOCATION        => $lang->absoluteT('kerio','ressource','type','location'),
            Kerio::RES_TYPE_EQUIPMENT       => $lang->absoluteT('kerio','ressource','type','equipment')
        ];

    }

    /**
     * @return HtmlDataJsonResponse
     */
    public function update()
    {
        $fieldToProtection = [
            'name',
            'status',
            'type',
            'description',
            'managert'
        ];

        foreach ($this->formData as $field => &$value)
        {
            $value = in_array($field, $fieldToProtection) ? htmlentities($value) : $value;
        }

        $attr = array(
            'description' => $this->formData['description'],
            'type' => $this->formData['type'],
            'isEnabled' => $this->formData['status'] === 'active' ? true : false,
            'manager' => array(
                'id' => $this->formData['manager'],
                'type' => 'UserPrincipal'
            )
        );

        $api = new KerioWhmcs('whmcsKerioEmail', 'Thurdata', '1.0');
        try {
            $api->login($this->getWhmcsParamByKey('serverhostname'), $this->getWhmcsParamByKey('serverusername'), $this->getWhmcsParamByKey('serverpassword'));
            $domainID = $api->getDomainId($this->getWhmcsParamByKey('domain'));
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }
        try {
            $result = $api->updateResouce($attr,$this->formData['id']);
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }
        $api->logout();
        return (new HtmlDataJsonResponse())->setMessageAndTranslate('ressourceHasBeenUpdated')->setStatusSuccess();
    }

    /**
     * @return HtmlDataJsonResponse
     */
    public function updateStatus()
    {
        $attr = array(
            'isEnabled' => $this->formData['status'] === 'active' ? true : false,
        );
        $api = new KerioWhmcs('whmcsKerioEmail', 'Thurdata', '1.0');
        try {
            $api->login($this->getWhmcsParamByKey('serverhostname'), $this->getWhmcsParamByKey('serverusername'), $this->getWhmcsParamByKey('serverpassword'));
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }
        try {
            $result = $api->updateResouce($attr,$this->formData['id']);
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }
        $api->logout();

        return (new HtmlDataJsonResponse())->setMessageAndTranslate('ressourceStatusHasBeenUpdated')->setStatusSuccess();

    }

    /**
     * @return HtmlDataJsonResponse
     */
    public function changePassword()
    {

    }
}