<?php

namespace ModulesGarden\Servers\ZimbraEmail\App\UI\Client\Ressource\Pages;

use ModulesGarden\Servers\ZimbraEmail\App\Helpers\BuildUrlExtended;
use ModulesGarden\Servers\ZimbraEmail\App\Helpers\ZimbraManager;
use ModulesGarden\Servers\ZimbraEmail\App\Libs\Product\ProductManager;
use ModulesGarden\Servers\ZimbraEmail\App\Libs\Zimbra\Components\Api\Soap\Connection;
use ModulesGarden\Servers\ZimbraEmail\App\Libs\Zimbra\Components\Api\Soap\Helpers\RessourceHelper;
use ModulesGarden\Servers\ZimbraEmail\App\Libs\Zimbra\Components\Api\Soap\Models\Ressource;
use ModulesGarden\Servers\ZimbraEmail\App\Libs\Zimbra\Components\Api\Soap\Repository\ClassOfServices;
use ModulesGarden\Servers\ZimbraEmail\App\Libs\Zimbra\Components\Filters\Ressources\FilterByCosId;
use ModulesGarden\Servers\ZimbraEmail\App\UI\Admin\Custom\Fields\EnabledField;
use ModulesGarden\Servers\ZimbraEmail\App\UI\Client\Ressource\Buttons\AddRessourceButton;
use ModulesGarden\Servers\ZimbraEmail\App\UI\Client\Ressource\Buttons\ChangePasswordButton;
use ModulesGarden\Servers\ZimbraEmail\App\UI\Client\Ressource\Buttons\ChangeStatusButton;
use ModulesGarden\Servers\ZimbraEmail\App\UI\Client\Ressource\Buttons\DeleteRessourceButton;
use ModulesGarden\Servers\ZimbraEmail\App\UI\Client\Ressource\Buttons\EditRessourceButton;
use ModulesGarden\Servers\ZimbraEmail\App\UI\Client\Ressource\Buttons\LoginToPanelButton;
use ModulesGarden\Servers\ZimbraEmail\App\UI\Client\Ressource\Buttons\MassChangeStatusButton;
use ModulesGarden\Servers\ZimbraEmail\App\UI\Client\Ressource\Buttons\MassDeleteRessourceButton;
use ModulesGarden\Servers\ZimbraEmail\App\UI\Client\Ressource\Buttons\SpanDropdownButton;
use function ModulesGarden\Servers\ZimbraEmail\Core\Helper\di;
use ModulesGarden\Servers\ZimbraEmail\Core\Models\Whmcs\Hosting;
use ModulesGarden\Servers\ZimbraEmail\Core\UI\Widget\Buttons\DropdawnButtonWrappers\ButtonDropdown;
use ModulesGarden\Servers\ZimbraEmail\Core\UI\Widget\DataTable\Column;
use ModulesGarden\Servers\ZimbraEmail\Core\UI\Widget\DataTable\DataProviders\DataProvider;
use ModulesGarden\Servers\ZimbraEmail\Core\UI\Interfaces\ClientArea;
use ModulesGarden\Servers\ZimbraEmail\Core\UI\Widget\DataTable\DataProviders\Providers\ArrayDataProvider;
use ModulesGarden\Servers\ZimbraEmail\Core\UI\Widget\DataTable\DataTable;

/**
 *
 * Created by PhpStorm.
 * User: Tomasz Bielecki ( tomasz.bi@modulesgarden.com )
 * 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('last_login'))
                ->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('zimbra','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] : '-';
    }

    /**
     * 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 ZimbraManager())
            ->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('zimbraCreateTimestamp')),
                'last_login'   => RessourceHelper::getFormattedData($ressource->getDataResourceA('zimbraLastLogonTimestamp'), 'd/m/Y H:i'),
                'type'         => $ressource->getDataResourceA('zimbraCalResType'),
                'status'       => $ressource->getDataResourceA('zimbraAccountStatus')
            ];

            $data[] = $ressourceArray;
        }

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

        $this->setDataProvider($dataProv);
    }

}