<?php

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

use ThurData\Servers\KerioEmail\App\Helpers\BuildUrlExtended;
use ThurData\Servers\KerioEmail\App\Helpers\KerioManager;
use ThurData\Servers\KerioEmail\App\Libs\Product\ProductManager;
use ThurData\Servers\KerioEmail\App\Libs\Kerio\Components\Api\Soap\Connection;
use ThurData\Servers\KerioEmail\App\Libs\Kerio\Components\Api\Soap\Helpers\RessourceHelper;
use ThurData\Servers\KerioEmail\App\Libs\Kerio\Components\Api\Soap\Models\Ressource;
use ThurData\Servers\KerioEmail\App\Libs\Kerio\Components\Api\Soap\Repository\ClassOfServices;
use ThurData\Servers\KerioEmail\App\Libs\Kerio\Components\Filters\Ressources\FilterByCosId;
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\ChangePasswordButton;
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\LoginToPanelButton;
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\Models\Whmcs\Hosting;
use ThurData\Servers\KerioEmail\Core\UI\Widget\Buttons\DropdawnButtonWrappers\ButtonDropdown;
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;

/**
 *
 * 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',
        'locked'        => 'default',
        'maintenance'   => 'warning',
        'closed'        => 'default',
        'lockout'       => 'info',
        'pending'       => 'warning',
        '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('date_created'))
                ->setOrderable()
                ->setSearchable(true))
            ->addColumn((new Column('capacity'))
                ->setOrderable()
                ->setSearchable(true))
            ->addColumn((new Column('type'))
                ->setOrderable()
                ->setSearchable(true, Column::TYPE_INT))
            ->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] == 'Location' ? di('lang')->absoluteT('kerio','ressource','type','location') : di('lang')->absoluteT('kerio','ressource','type','equipment');
    }

    /**
     * load buttons
     */
    public function initContent()
    {
        $productManager = new ProductManager();
        $productManager->loadByHostingId($this->getRequestValue('id'));

        $this->addMassActionButton(new MassChangeStatusButton());
        $this->addMassActionButton(new MassDeleteRessourceButton());

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


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

        $mailBox = new LoginToPanelButton();
        $mailBox
            ->setRawUrl(BuildUrlExtended::getProvisioningUrl('webmail', true, true,'clientSso'))
            ->setRedirectParams(['actionElementId' => 'true']);

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

        if ($productManager->get('ca_logInToMailboxButton') === 'on')
        {
            $actions->addButton($mailBox);
        }

        $this->addActionButton($actions);

    }

    /**
     * load data
     */
    public function loadData()
    {
        /**
         * load hosting
         */
        $hosting = Hosting::where('id', $this->getRequestValue('id'))->first();


        $ressources = (new KerioManager())
            ->getApiByServer($hosting->server)
            ->soap
            ->repository()
            ->ressources
            ->getByDomainName($hosting->domain);

        /**
         * format model to array
         */
        $data = [];
        foreach ($ressources as $ressource)
        {
            /* @var $account Ressource */

            $ressourceArray = [
                'id'           => $ressource->getId(),
                'ressource'    => $ressource->getDataResourceA('displayName'),
                'date_created' => RessourceHelper::getFormattedData($ressource->getDataResourceA('kerioCreateTimestamp')),
//                'last_login'   => RessourceHelper::getFormattedData($ressource->getDataResourceA('kerioLastLogonTimestamp'), 'd/m/Y H:i'),
                'capacity'     => $ressource->getDataResourceA('kerioCalResCapacity'),
                'type'         => $ressource->getDataResourceA('kerioCalResType'),
                'status'       => $ressource->getDataResourceA('kerioAccountStatus')
            ];

            $data[] = $ressourceArray;
        }

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

        $this->setDataProvider($dataProv);
    }

}