<?php
namespace ModulesGarden\Servers\OpenXchange\App\UI\Client\EmailCatchAll\Providers;

use ModulesGarden\Servers\OpenXchange\App\Libs\RestApi;
use ModulesGarden\Servers\OpenXchange\App\Helpers\Helper;
use ModulesGarden\Servers\OpenXchange\Core\UI\ResponseTemplates\HtmlDataJsonResponse;
use ModulesGarden\Servers\OpenXchange\Core\UI\Widget\Forms\DataProviders\BaseDataProvider;

/**
 *
 * Created by PhpStorm.
 * User: Tomasz Bielecki ( tomasz.bi@modulesgarden.com )
 * Date: 18.09.19
 * Time: 11:50
 * Class AddEmailCatchAllDataProvider
 */
class AddEmailCatchAllDataProvider extends BaseDataProvider
{

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

        foreach($users as $user)    
        {
            if($user->isContextAdmin == true)
            {
                continue;
            }
            $this->availableValues['catchall'][$user->name] = Helper::convertEmailFromPunnycode($user->mail);
        }

        $this->data['domain'] = $params['domain'];
    }

    public function create()
    {
        try
        {
            $hid     = $this->getRequestValue('id');
            $params  = Helper::moduleParams($hid);
            $context = new RestApi($params);
            $result  = $context->createDomainCatchall($this->formData['catchall']);

            return (new HtmlDataJsonResponse())->setMessageAndTranslate('EmailCatchAllHasBeenCreated')->setStatusSuccess();
            
        }
        catch(\Exception $e)
        {
            return (new HtmlDataJsonResponse())->setMessageAndTranslate('CannotCreateDomainCatchAll')->setStatusError();
        }
    }

    public function update()
    {
        
    }
}
