<?php

namespace ModulesGarden\Servers\OpenXchange\App\UI\Client\EmailAccount\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\EmailAccount\Buttons\AddAccountButton;
use ModulesGarden\Servers\OpenXchange\Core\UI\Widget\DataTable\DataProviders\DataProvider;
use ModulesGarden\Servers\OpenXchange\App\UI\Client\EmailAccount\Buttons\EditAccountButton;
use ModulesGarden\Servers\OpenXchange\App\UI\Client\EmailAccount\Buttons\DeleteAccountButton;
use ModulesGarden\Servers\OpenXchange\Core\UI\Widget\DataTable\DataProviders\Providers\ArrayDataProvider;
use ModulesGarden\Servers\OpenXchange\App\Models\ProductConfiguration;
use ModulesGarden\Servers\OpenXchange\App\UI\Client\EmailAccount\Constants;
use ModulesGarden\Servers\OpenXchange\App\Models\MailboxDeleteList;

class EmailAccount extends DataTable implements ClientArea
{
    protected $id    = 'accounts';
    protected $name  = 'accounts';
    protected $title = null;


       /**
     * labels for statuses
     */
    const STATUS_LABEL = [
        'success' => 'success',
        'warning' => 'warning'
    ];
    /**
     * load columns
     */
    protected function loadHtml()
    {
        $params       = Helper::moduleParams($_REQUEST['id']);
        $freeAccounts = Helper::freeAccountsLimit($params);

        /*if ($freeAccounts > 0)
        {*/
            $this
            ->addColumn((new Column('id'))
                ->setOrderable(DataProvider::SORT_DESC)
                ->setSearchable(true, Column::TYPE_STRING))
            ->addColumn((new Column('display_name'))
                ->setOrderable()
                ->setSearchable(true))
            ->addColumn((new Column('primaryEmail'))
                ->setOrderable()
                ->setSearchable(true))
            ->addColumn((new Column('maxQuota'))
                ->setOrderable()
                ->setSearchable(true))
            ->addColumn((new Column('usedQuota'))
                ->setOrderable()
                ->setSearchable(true))
            ->addColumn((new Column('type'))
                ->setOrderable()
                ->setSearchable(true));
            /*->addColumn((new Column('mailenabled'))
                ->setOrderable()
                ->setSearchable(true));*/
        /*}
        else
        {
            $this
            ->addColumn((new Column('id'))
                ->setOrderable(DataProvider::SORT_DESC)
                ->setSearchable(true, Column::TYPE_STRING))
            ->addColumn((new Column('display_name'))
                ->setOrderable()
                ->setSearchable(true))
            ->addColumn((new Column('primaryEmail'))
                ->setOrderable()
                ->setSearchable(true))
            ->addColumn((new Column('maxQuota'))
                ->setOrderable()
                ->setSearchable(true))
            ->addColumn((new Column('usedQuota'))
                ->setOrderable()
                ->setSearchable(true));
        }*/
    }

    /**
     * load buttons
     */
    public function initContent()
    {
        $this->addButton(new AddAccountButton());
        $this->addActionButton(new EditAccountButton());
        $this->addActionButton(new DeleteAccountButton());
    }

    /**
     * load data
     */
    public function loadData()
    {
        $data            = [];
        $params          = Helper::moduleParams($_REQUEST['id']);
        $config          = ProductConfiguration::config($params['packageid']);
        $selectedProduct = $config['selected_product'];

        $context   = new RestApi($params);
        $usersList = $context->listAllUsers();

        $freeAccounts = Helper::freeAccountsLimit($params);

        foreach($usersList as $user)
        {
            if($user->isContextAdmin == true)
            {
                continue;
            }
            
            $userIdUnicode   = Helper::convertEmailFromPunnycode($user->name);
            $userNAmeUnicode = Helper::convertEmailFromPunnycode($user->mail);

            $accountArray = [
                //'id'            => $user->name,
                //'primaryEmail'  => $user->mail,
                'id'            => $userIdUnicode,
                'primaryEmail'  => $userNAmeUnicode,
                'display_name'  => $user->displayName,
                'maxQuota'      => property_exists($user, 'unifiedQuota') ? $user->unifiedQuota : $user->mailQuota,
                'usedQuota'     => $user->usedQuota,
                //'mailenabled'   => $user->webLoginEnabled,
            ];
            
            //if ($freeAccounts > 0)
            //{
                $accountArray['type'] = $this->getEmailType($user, $selectedProduct);
            //}

            $data[] = $accountArray;
        }

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

    private function getEmailType($data, $selectedProduct)
    {
        $type          = '';
        $addon         = '';
        $accAttributes = $data->classOfService;

        if (in_array('cloud_productivity', $accAttributes) && in_array('guard', $accAttributes) && count($accAttributes) == 2)
        {
            if ($selectedProduct == 'cloud_productivity_guard')
            {
                //$type = $availableTypes['cloud_productivity_guard'];
                $type = array_search('cloud_productivity_guard', Constants::getTranslatedTypes());
            }
            else
            {
                foreach ($accAttributes as $attribute)
                {
                    if (array_search($attribute, Constants::getTranslatedTypes()))
                    {
                        //$type = $availableTypes[$attribute];
                        $type = array_search($attribute, Constants::getTranslatedTypes());
                    }

                    if(array_search($attribute, Constants::getTranslatedAddonTypes()))
                    {
                        $addon = $addon.' + '.array_search($attribute, Constants::getTranslatedAddonTypes());
                    }
                }
            }
        }
        else
        {
            foreach ($accAttributes as $attribute)
            {
                if ($selectedProduct == 'cloud_productivity_guard' && ($attribute == 'cloud_productivity' || $attribute == 'guard'))
                {
                    //$type = $availableTypes['cloud_productivity_guard'];
                    $type = array_search('cloud_productivity_guard', Constants::getTranslatedTypes());
                    continue;
                }
                elseif (array_search($attribute, Constants::getTranslatedTypes()))
                {
                    //$type = $availableTypes[$attribute];
                    $type = array_search($attribute, Constants::getTranslatedTypes());
                }

                if(array_search($attribute, Constants::getTranslatedAddonTypes()))
                {
                    $addon = $addon.' + '.array_search($attribute, Constants::getTranslatedAddonTypes());
                }
            }
        }

        if (!$type || $type == '')
        {
            $type = '---';
        }

        return $type.$addon;
    }

    public function replaceFieldMailenabled($key, $row)
    {
      
        $row['mailenabled'] === true ? $status = 'success' : $status = 'warning';
        $field = new EnabledField();
        $field->setEnabled($row['mailenabled']);

        return $field->getHtml();
    }

    public function replaceFieldUsedQuota($key, $row)
    {
      
        if(empty($row['usedQuota'])){
            $row['usedQuota'] = 0;
        }
        return $row['usedQuota'].' MB';
    }

    public function replaceFieldMaxQuota($key, $row)
    {
      
        if($row['maxQuota'] == '-1'){
            return 'Unlimited';
        }
        return $row['maxQuota'].' MB';
    }
    
    public function replaceFieldId($key, $row)
    {
        //check if delete request exists for this mailbox
        $deleteRequestExists = MailboxDeleteList::where('mailbox_name', '=', $row['id'])->exists();

        if ($deleteRequestExists)
        {
            return '<del>'.$row['id'].'</del>';
        }

        return $row['id'];
    }
}
