<?php

namespace ModulesGarden\Servers\OpenXchange\App\UI\Client\EmailForwarder\Pages;

use ModulesGarden\Servers\OpenXchange\App\Libs\RestApi;
use ModulesGarden\Servers\OpenXchange\App\Helpers\Helper;
use ModulesGarden\Servers\OpenXchange\Core\UI\Interfaces\ClientArea;
use ModulesGarden\Servers\OpenXchange\Core\UI\Widget\DataTable\Column;
use ModulesGarden\Servers\OpenXchange\Core\UI\Widget\DataTable\DataTable;
use ModulesGarden\Servers\OpenXchange\App\UI\Client\Others\Fields\EnabledField;
use ModulesGarden\Servers\OpenXchange\App\UI\Client\EmailForwarder\Buttons\AddForwarderButton;
use ModulesGarden\Servers\OpenXchange\App\UI\Client\EmailForwarder\Buttons\EditForwarderButton;
use ModulesGarden\Servers\OpenXchange\App\UI\Client\EmailForwarder\Buttons\DeleteForwarderButton;
use ModulesGarden\Servers\OpenXchange\Core\UI\Widget\DataTable\DataProviders\Providers\ArrayDataProvider;

class EmailForwarder extends DataTable implements ClientArea
{
    protected $id    = 'forwarders';
    protected $name  = 'forwarders';
    protected $title = null;

    /**
     * load columns
     */
    protected function loadHtml()
    {
        $this
        ->addColumn((new Column('primaryEmail'))
            ->setOrderable()
            ->setSearchable(true))
        ->addColumn((new Column('forwarder'))
            ->setOrderable()
            ->setSearchable(true));
    }

    /**
     * load buttons
     */
    public function initContent()
    {
        $this->addButton(new AddForwarderButton());
        //$this->addActionButton(new EditForwarderButton());
        $this->addActionButton(new DeleteForwarderButton());
    }

    /**
     * load data
     */
    public function loadData()
    {
        $data   = [];
        $params = Helper::moduleParams($_REQUEST['id']);
     
        $api        = new RestApi($params);
        $forwarders = $api->getForwarders();

        foreach($forwarders as $key => $forwarder)
        {
           $data[] = [
               'id'           => Helper::convertEmailFromPunnycode($forwarder->address),
               'primaryEmail' => Helper::convertEmailFromPunnycode($forwarder->address),
               'forwarder'    => Helper::convertEmailFromPunnycode($forwarder->forwardTo[0])
           ];
        }
        
        $dataProv = new ArrayDataProvider();
        $dataProv->setDefaultSorting('mailbox', 'ASC')->setData($data);
        $this->setDataProvider($dataProv);
    }
}
