<?php

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

use ThurData\Servers\KerioEmail\App\UI\Admin\Custom\Fields\EnabledField;
use ThurData\Servers\KerioEmail\App\UI\Client\Ressource\Buttons\AddRessourceButton;
use ThurData\Servers\KerioEmail\App\UI\Client\Ressource\Buttons\ChangeStatusButton;
use ThurData\Servers\KerioEmail\App\UI\Client\Ressource\Buttons\DeleteRessourceButton;
use ThurData\Servers\KerioEmail\App\UI\Client\Ressource\Buttons\EditRessourceButton;
use ThurData\Servers\KerioEmail\App\UI\Client\Ressource\Buttons\MassChangeStatusButton;
use ThurData\Servers\KerioEmail\App\UI\Client\Ressource\Buttons\MassDeleteRessourceButton;
use ThurData\Servers\KerioEmail\App\UI\Client\Ressource\Buttons\SpanDropdownButton;
use function ThurData\Servers\KerioEmail\Core\Helper\di;
use ThurData\Servers\KerioEmail\Core\UI\Widget\DataTable\Column;
use ThurData\Servers\KerioEmail\Core\UI\Widget\DataTable\DataProviders\DataProvider;
use ThurData\Servers\KerioEmail\Core\UI\Interfaces\ClientArea;
use ThurData\Servers\KerioEmail\Core\UI\Widget\DataTable\DataProviders\Providers\ArrayDataProvider;
use ThurData\Servers\KerioEmail\Core\UI\Widget\DataTable\DataTable;
use ThurData\Servers\KerioEmail\Api\KerioWhmcs;

/**
 *
 * Created by PhpStorm.
 * User: ThurData
 * Date: 10.09.19
 * Time: 10:51
 * Class Ressources
 */
class Ressources extends DataTable implements ClientArea
{

    /**
     * labels for statuses
     */
    const STATUS_LABEL = [
        'active'        => 'success',
        'closed'        => 'default',
        'default'       => 'default'
    ];

    protected $id    = 'ressources';
    protected $name  = 'ressources';
    protected $title = null;

    /**
     * load columns
     */
    protected function loadHtml()
    {
        $this
            ->addColumn((new Column('ressource'))
                ->setOrderable(DataProvider::SORT_ASC)
                ->setSearchable(true, Column::TYPE_STRING))
            ->addColumn((new Column('description'))
                ->setOrderable()
                ->setSearchable(true, Column::TYPE_STRING))
            ->addColumn((new Column('type'))
                ->setOrderable()
                ->setSearchable(true, Column::TYPE_STRING))
            ->addColumn((new Column('manager'))
                ->setOrderable()
                ->setSearchable(true, Column::TYPE_STRING))
            ->addColumn((new Column('status'))
                ->setOrderable()
                ->setSearchable(true));
    }

    /**
     * @param $key
     * @param $row
     * @return mixed
     */
    public function replaceFieldStatus($key, $row)
    {
        $status = self::STATUS_LABEL[$row[$key]] ? self::STATUS_LABEL[$row[$key]] : self::STATUS_LABEL['default'];
        $label = di('lang')->absoluteT('kerio','account','status',$row[$key]);

        $field = new EnabledField();
        $field->setRawType($status);
        $field->setRawTitle($label);

        return $field->getHtml();
    }

    /**
     * @param $key
     * @param $row
     * @return mixed
     */
    public function replaceFieldLast_login($key, $row)
    {
        return $row[$key] ? $row[$key] : '-';
    }

    /**
     * @param $key
     * @param $row
     * @return mixed
     */
    public function replaceFieldType($key, $row)
    {
        return $row[$key] == 'Room' ? di('lang')->absoluteT('kerio','ressource','type','location') : di('lang')->absoluteT('kerio','ressource','type','equipment');
    }

    /**
     * load buttons
     */
    public function initContent()
    {
        $this->addMassActionButton(new MassChangeStatusButton());
        $this->addMassActionButton(new MassDeleteRessourceButton());

        $this->addButton(new AddRessourceButton());


        $this->addActionButton(new EditRessourceButton());
        $this->addActionButton(new DeleteRessourceButton());

        $actions = new SpanDropdownButton('actions');
        $actions->addButton(new ChangeStatusButton());

        $this->addActionButton($actions);

    }

    /**
     * load data
     */
    public function loadData()
    {
        $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()];
        }
        $fields = array(
            "id",
            "name",
            "description",
            "type",
            "isEnabled",
            "manager");
        try {
            $ressources = $api->getResources($fields, $domainID);
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }
        $api->logout();

        /**
         * format model to array
         */
        $data = [];
        foreach ($ressources as $ressource)
        {
            $ressourceArray = [
                'id'           => $ressource['id'],
                'ressource'    => $ressource['name'],
                'description'  => $ressource['description'],
                'type'         => $ressource['type'],
                'manager'      => $ressource['manager']['name'] . '@' . $ressource['manager']['domainName'],
                'status'       => $ressource['isEnabled'] ? 'active' : 'default'
            ];

            $data[] = $ressourceArray;
        }
        $dataProv = new ArrayDataProvider();
        $dataProv->setDefaultSorting('ressource', 'ASC')->setData($data);

        $this->setDataProvider($dataProv);
    }

}