<?php

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

use ModulesGarden\Servers\OpenXchange\App\Libs\RestApi;
use ModulesGarden\Servers\OpenXchange\App\Helpers\Helper;
use function \ModulesGarden\Servers\OpenXchange\Core\Helper\di;
use ModulesGarden\Servers\OpenXchange\Core\UI\Widget\Others\Label;
use ModulesGarden\Servers\OpenXchange\Core\UI\Interfaces\AdminArea;
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\Traits\RequestObjectHandler;
use ModulesGarden\Servers\OpenXchange\Core\UI\Interfaces\AjaxElementInterface;
use ModulesGarden\Servers\OpenXchange\App\UI\Client\Others\Fields\EnabledField;
use ModulesGarden\Servers\OpenXchange\App\UI\Client\Home\Fields\PasswordElement;
use ModulesGarden\Servers\OpenXchange\Core\UI\Widget\DataTable\DataProviders\Providers\ArrayDataProvider;
use ModulesGarden\Servers\OpenXchange\App\Models\ProductConfiguration;


class ServiceInformation extends DataTable implements ClientArea, AdminArea, AjaxElementInterface
{
    use RequestObjectHandler;

    protected $id          = 'serviceInformation';
    protected $title       = 'serviceInformation';
    protected $searchable  = false;
    protected $tableLength = "0";
    protected $isViewFooter = false;
    protected $isViewTopBody = false;

    public function noThead()
    {
        return true;
    }

    protected function loadHtml()
    {
        $this->addColumn((new Column('name')))->addColumn((new Column('value')));
    }

    public function replaceFieldValue($key, $row)
    {
        if($row['value'] === true || $row['value'] === false)
        {
            $row['value'] === true ? $status = 'success' : $status = 'warning';
            $field = new EnabledField();
            $field->setEnabled($row['value']);
    
            return $field->getHtml();
        }

        return $row[$key];
    }

    public function replaceFieldName($key, $row)
    {
        return '<b>'.$row[$key].'</b>';
    }

    protected function loadData()
    {
        $dataProvider = new ArrayDataProvider();
        $hostingId = $this->request->get('id');
        if(empty($hostingId)){
            $hostingId = $_SESSION['serviceid'];
        }
        $params = Helper::moduleParams($hostingId);

        //$context = new OXContext($params);
        $context = new RestApi($params);//getContextInfo
        $contextData = $context->getContextInfo();
        //$user = $context->list();

        //$contextData = $context->getData($user->return->name);

        $dataProvider->setData($this->prepareData($contextData, $context, $params));
        $this->setDataProvider($dataProvider);
    }

    public function initContent()
    {
        $this->loadRequestObj();

    }

    public function getTableLength()
    {
        return $this->tableLength;
    }

    public function prepareData($contextData, $context, $params)
    {
        $lang = di('lang');
        /*$data[] = [
            'name' => $lang->T('status') , 'value' => $contextData->return->enabled
        ];*/
        /*$data[] = [
            'name' => $lang->T('ownerName') , 'value' => $contextData->return->owner->displayname
        ];*/
        $settings             = $context->getSettings();
        $accLimit             = Helper::accountsLimit($params);
        $aliasLimit           = Helper::aliasesLimit($params);
        $forwardingAliasLimit = Helper::forwardingAliasesLimit($params);
        
        //check if there was some free accounts for this product (freemium model)
        $freeAcc         = Helper::freeAccountsLimit($params);
        $accProdLimit    = Helper::accountsProdLimit($params);
        $accSecLimit     = Helper::accountsSecLimit($params);
        $accProdSecLimit = Helper::accountsProdSecLimit($params);
        $accGuardLimit   = Helper::accountsGuardLimit($params);
        $accAiLimit      = Helper::accountsAiLimit($params);

        $api             = new RestApi($params);
        $forwarders      = json_decode(json_encode([$api->getForwarders()]), true);
        $countForwarders = count($forwarders[0]);
        
        //detemine selected product
        $config = ProductConfiguration::config($params['packageid']);

        if ($config['selected_product'] == 'cloud_pim')
        {
            $selectedProduct = 'usedEmailAccsEss';
        }
        elseif ($config['selected_product'] == 'cloud_single_web')
        {
            $selectedProduct = 'usedEmailAccsBasic';
        }
        elseif ($config['selected_product'] == 'cloud_productivity_guard')
        {
            $selectedProduct = 'usedEmailAccsPremium';
        }

        /*$moduleAccess = [
            'cloud_pim'                   => 'Mail Essential',
            'cloud_productivity'          => "Add-on Productivity",
            'cloud_security'              => "Add-on Security",
            'cloud_productivity_security' => "Add-on Productivity & Security"
        ];*/
        /*$data[] = [
            'name' => $lang->T('moduleAccess') , 'value' => $moduleAccess[$settings['module_access']]
        ];*/
        /*$data[] = [
            'name' => $lang->T('usedQuotaData') , 'value' => $contextData->maxQuota.' MB'
        ];*/

        //$contextUser = new OXUser($params);
        $users = $context->listAllUsers();

        if(!is_array($users))
        {
            $users = [$users];
        }
        $aliasCount = 0;
        $userAdmin  = false;
        //$usersData  = (array)$contextUser->getMultipleData($users)->return;
        
        foreach($users as $key => &$user)
        {
            if (is_object($user))
            {
                if($user->isContextAdmin == true && !$userAdmin)
                {
                    $userAdmin = true;
                    /*$data[] = [
                        'name' => $lang->T('contextAdminUsername'), 'value' => $params['username']
                    ];*/
                    /*$data[] = [
                        'name' => $lang->T('contextAdminPassword'), 'value' =>  (new PasswordElement())->setValue($params['password'])->getHtml()
                    ];*/
                    unset($users[$key]);
                    continue;
                }

                $aliases = $user->aliases;

                if (!is_array($aliases)) {
                    $aliases = [$aliases];
                }

                foreach($aliases as $alias)
                {
                    $aliasCount++;
                }
            }
            else
            {
                if($users['contextadmin'] == true && !$userAdmin)
                {
                    /*$data[] = [
                        'name' => $lang->T('contextAdminUsername'), 'value' => $params['username']
                    ];*/
                    $data[] = [
                        'name' => $lang->T('contextAdminPassword'), 'value' =>  (new PasswordElement())->setValue($params['password'])->getHtml()
                    ];

                    $users = [];

                    continue;
                }
            }
        }

        /*if ($freeAcc && $freeAcc > 0)
        {*/
            $emailAccs        = 0;
            $emailProdAccs    = 0;
            $emailSecAccs     = 0;
            $emailProdSecAccs = 0;
            $emailGuardAccs   = 0;
            $emailAiAccs      = 0;

            foreach ($users as $account)
            {
                $accAttributes = $account->classOfService;

                if (!is_array($accAttributes))
                {
                    continue;
                }

                if ((in_array('cloud_pim', $accAttributes) || in_array('cloud_single_web', $accAttributes)) && count($accAttributes) == 1)
                {
                    $emailAccs++;
                }
                elseif ((in_array('cloud_productivity', $accAttributes) && in_array('guard', $accAttributes)) && count($accAttributes) == 2)
                {
                    if ($selectedProduct == 'usedEmailAccsPremium' && $config['product_accounts'] && $config['product_accounts'] > 0)
                    {
                        $emailAccs++;
                    }
                    else
                    {
                        $emailProdAccs++;
                        $emailGuardAccs++;
                    }
                }
                elseif ((in_array('cloud_productivity', $accAttributes) && in_array('guard', $accAttributes)) && in_array('ai', $accAttributes))
                {
                    if ($selectedProduct == 'usedEmailAccsPremium' && $config['product_accounts'] && $config['product_accounts'] > 0)
                    {
                        $emailAccs++;
                        $emailAiAccs++;
                    }
                    else
                    {
                        $emailProdAccs++;
                        $emailGuardAccs++;
                        $emailAiAccs++;
                    }
                }
                else
                {
                    if (in_array('cloud_pim', $accAttributes))
                    {
                        $emailAccs++;
                    }
                    if (in_array('cloud_single_web', $accAttributes))
                    {
                        $emailAccs++;
                    }
                    if (in_array('cloud_productivity', $accAttributes))
                    {
                        $emailProdAccs++;
                    }
                    if(in_array('cloud_security', $accAttributes))
                    {
                        $emailSecAccs++;
                    }
                    if (in_array('cloud_productivity_security', $accAttributes))
                    {
                        $emailProdSecAccs++;
                    }
                    if (in_array('guard', $accAttributes))
                    {
                        $emailGuardAccs++;
                    }
                    if (in_array('ai', $accAttributes))
                    {
                        $emailAiAccs++;
                    }
                }

                //foreach ($accAttributes as $attribute)
                //{
                    /*if ($attribute->key == 'cloud')
                    {
                        $accType = $attribute->value->entries->value;*/

                        /*if ($attribute == 'cloud_pim' || $attribute == 'cloud_single_web')
                        {
                            $emailAccs++;
                        }
                        elseif ($attribute == 'cloud_productivity')
                        {
                            $emailProdAccs++;
                        }
                        elseif($attribute == 'cloud_security')
                        {
                            $emailSecAccs++;
                        }
                        elseif ($attribute == 'cloud_productivity_security')
                        {
                            $emailProdSecAccs++;
                        }
                        elseif ($attribute == 'guard')
                        {
                            $emailGuardAccs++;
                        }
                        elseif ($attribute == 'ai')
                        {
                            $emailAiAccs++;
                        }

                        break;*/
                    //}
                //}
            }
        /*}
        else
        {
            $emailAccs = count($users);
        }*/

        /*if ($freeAcc > 0)
        {*/
        if ($accLimit)
        {
            if ($accLimit == 'unlimited')
            {
                $data[] = [
                    'name' => $lang->T($selectedProduct) , 'value' => (string)$emailAccs.'/'.'Unlimited'
                ];
            }
            elseif ($accLimit > 0)
            {
                $data[] = [
                    'name' => $lang->T($selectedProduct) , 'value' => (string)$emailAccs.'/'.($accLimit + $freeAcc)
                ];
            }
        }
        /*}
        else
        {
            $data[] = [
                'name' => $lang->T('usedEmailAccs') , 'value' => $emailAccs.'/'.($accLimit + $freeAcc)
            ];
        }*/

        if ($accProdLimit)
        {
            if ($accProdLimit == 'unlimited')
            {
                $data[] = [
                    'name' => $lang->T('usedEmailProdAccs') , 'value' => (string)$emailProdAccs.'/'.'Unlimited'
                ];
            }
            elseif ($accProdLimit > 0)
            {
                $data[] = [
                    'name' => $lang->T('usedEmailProdAccs') , 'value' => (string)$emailProdAccs.'/'.$accProdLimit
                ];
            }
        }

        if ($accSecLimit)
        {
            if ($accSecLimit == 'unlimited')
            {
                $data[] = [
                    'name' => $lang->T('usedEmailSecAccs') , 'value' => (string)$emailSecAccs.'/'.'Unlimited'
                ];
            }
            elseif ($accSecLimit > 0)
            {
                $data[] = [
                    'name' => $lang->T('usedEmailSecAccs') , 'value' => (string)$emailSecAccs.'/'.$accSecLimit
                ];
            }
        }
        
        if ($accProdSecLimit)
        {
            if ($accProdSecLimit == 'unlimited')
            {
                $data[] = [
                    'name' => $lang->T('usedEmailProdSecAccs') , 'value' => (string)$emailProdSecAccs.'/'.'Unlimited'
                ];
            }
            elseif ($accProdSecLimit > 0)
            {
                $data[] = [
                    'name' => $lang->T('usedEmailProdSecAccs') , 'value' => (string)$emailProdSecAccs.'/'.$accProdSecLimit
                ];
            }
        }

        if ($accGuardLimit)
        {
            if ($accGuardLimit == 'unlimited')
            {
                $data[] = [
                    'name' => $lang->T('usedEmailGuardAccs') , 'value' => (string)$emailGuardAccs.'/'.'Unlimited'
                ];
            }
            elseif ($accGuardLimit > 0)
            {
                $data[] = [
                    'name' => $lang->T('usedEmailGuardAccs') , 'value' => (string)$emailGuardAccs.'/'.$accGuardLimit
                ];
            }
        }

        if ($accAiLimit)
        {
            if ($accAiLimit == 'unlimited')
            {
                $data[] = [
                    'name' => $lang->T('usedEmailAiAccs') , 'value' => (string)$emailAiAccs.'/'.'Unlimited'
                ];
            }
            elseif ($accAiLimit > 0)
            {
                $data[] = [
                    'name' => $lang->T('usedEmailAiAccs') , 'value' => (string)$emailAiAccs.'/'.$accAiLimit
                ];
            }
        }

        $data[] = [
            'name' => $lang->T('usedAliases') , 'value' => ($aliasCount - count($users)).'/'.($aliasLimit + $freeAcc)
        ];

        $data[] = [
            'name' => $lang->T('usedForwarders') , 'value' => $countForwarders.'/'.$forwardingAliasLimit
        ];

        return $data;
    }
}
