<?php

namespace ModulesGarden\Servers\OpenXchange\App\UI\Client\EmailAlias\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: 12:59
 * Class DeleteEmailAliasDataProvider
 */
class DeleteEmailAliasDataProvider extends BaseDataProvider
{

    public function read()
    {
        $params = json_decode(base64_decode($this->actionElementId), true);

        $this->data['id']    = $params['user_id'];
        $this->data['alias'] = $params['alias'];
    }

    public function update()
    {

    }

    public function delete()
    {
        $hid    = $this->getRequestValue('id');
        $params = Helper::moduleParams($hid);

        $context = new RestApi($params);
        $user    = $context->getUserData(Helper::convertEmailToPunnycode($this->formData['id']));
        $aliases = $user->aliases;

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

        foreach($aliases as $key => &$alias)
        {
            if($alias == Helper::convertEmailToPunnycode($this->formData['alias']))
            {
                unset($aliases[$key]);
                break;
            }
        }
   
        $newAliases = [];

        foreach($aliases as $key => &$alias)
        {
            $newAliases[] = $alias;
        }

        $result = $context->addAliases(Helper::convertEmailToPunnycode($this->formData['id']), $newAliases);
        
        if ($result == '')
        {
            return (new HtmlDataJsonResponse())->setMessageAndTranslate('emailAliasHasBeenDeleted')->setStatusSuccess();
        }
        else
        {
            return (new HtmlDataJsonResponse())->setMessageAndTranslate('emailAliasHasBeenDeleted')->setStatusSuccess();
        }
    }
}
