<?php

namespace ModulesGarden\Servers\OpenXchange\App\UI\Client\EmailCatchAll\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\Core\UI\Widget\DataTable\DataProviders\DataProvider;
use ModulesGarden\Servers\OpenXchange\App\UI\Client\EmailCatchAll\Buttons\AddEmailCatchAllButton;
use ModulesGarden\Servers\OpenXchange\App\UI\Client\EmailCatchAll\Buttons\DeleteEmailCatchAllButton;
use ModulesGarden\Servers\OpenXchange\Core\UI\Widget\DataTable\DataProviders\Providers\ArrayDataProvider;

class EmailCatchAll extends DataTable implements ClientArea
{

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

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

    public function initContent()
    {
        $this->addButton(new AddEmailCatchAllButton());
        $this->addActionButton(new DeleteEmailCatchAllButton());
    }

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

        $userDetails = [];

        foreach ($users as $user)
        {
            if($user->isContextAdmin == true)
            {
                continue;
            }

            $userDetails[$user->name] = $user->mail;
        }

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

        $output  = [];
        $params  = Helper::moduleParams($_REQUEST['id']);
        $data    = $context->listDomainCatchall();

        foreach ($data as $dat)
        {
            $output[0]['domain']       = $params['domain'];
            $output[0]['primaryEmail'] = Helper::convertEmailFromPunnycode($userDetails[$dat->login]);
            $output[0]['id']           =  base64_encode(json_encode([
               'username' => $dat->login
            ]));
        }

        $dataProv = new ArrayDataProvider();
        $dataProv->setDefaultSorting('mailbox', 'ASC')->setData($output);
        $this->setDataProvider($dataProv);
    }
}
