<?php


namespace ModulesGarden\ProxmoxAddon\App\Listeners\Vps;


use ModulesGarden\ProxmoxAddon\App\Events\Vps\VmReinstalledEvent;
use ModulesGarden\ProxmoxAddon\App\Services\ApiService;
use ModulesGarden\ProxmoxAddon\App\Services\EmailService;
use ModulesGarden\ProxmoxAddon\App\Services\Vps\HighAvailabilityClusterService;
use ModulesGarden\ProxmoxAddon\App\Services\Vps\IpSetIpFilterService;
use ModulesGarden\ProxmoxAddon\App\Services\Vps\NetworkService;
use ModulesGarden\ProxmoxAddon\App\Services\Vps\ProductService;
use ModulesGarden\ProxmoxAddon\App\Services\Vps\UserService;
use ModulesGarden\ProxmoxAddon\Core\UI\Traits\WhmcsParams;

class VmReinstalledListener
{
    use WhmcsParams;
    use ApiService;
    use UserService;
    use ProductService;

    /**
     * @var IpSetIpFilterService
     */
    private $ipSetFilterService;
    private $emailService;
    /**
     * @var  HighAvailabilityClusterService
     */
    protected $highAvailabilityClusterService;

    public function __construct()
    {
        $this->ipSetFilterService             = new IpSetIpFilterService();
        $this->emailService                   = new EmailService();
        $this->highAvailabilityClusterService = new HighAvailabilityClusterService();
        $this->networkService = new NetworkService();
    }

    public function handle(VmReinstalledEvent $event)
    {
        //IP Set
        if ($this->configuration()->isIpsetIpFilter())
        {
            $this->ipSetFilterService->create();
        }
        //User permission
        $this->userUpdate();
        //HA
        if ($this->highAvailabilityClusterService->isConfigured() && !$this->highAvailabilityClusterService->exist())
        {
            $this->highAvailabilityClusterService->create();
        }
        if (!$this->vm()->isRunning() && $this->configuration()->isStart())
        {
            $this->vm()->start();
        }
        //Reinstall notification
        if ($this->configuration()->getReinstallEmailTemplateId())
        {
            $user = $this->getUser()->toArray();
            $user['password'] = decrypt($user['password']);
            $this->emailService->template($this->configuration()->getReinstallEmailTemplateId())
                ->vars(["id" => $this->getWhmcsParamByKey("serviceid"),
                           'customvars' => base64_encode(serialize(['user' => $user ]))
                       ])
                ->send();
        }
    }
}