<?php

namespace ModulesGarden\ProxmoxAddon\App\Jobs\Cloud\Reinstall;

use ModulesGarden\ProxmoxAddon\App\Jobs\BaseJob;
use ModulesGarden\ProxmoxAddon\App\Models\VirtualInterface;
use ModulesGarden\ProxmoxAddon\App\Models\VmIpAddress;
use ModulesGarden\ProxmoxAddon\App\Services\Cloud\ContainerService;
use ModulesGarden\ProxmoxAddon\App\Services\Cloud\HighAvailabilityClusterService;
use ModulesGarden\ProxmoxAddon\App\Services\Cloud\ProductService;
use function ModulesGarden\ProxmoxAddon\Core\Helper\sl;

class DeleteVmJob extends BaseJob
{
    use ProductService;

    /**
     * @var  HighAvailabilityClusterService
     */
    protected $highAvailabilityClusterService;

    protected function initServices()
    {

        $this->highAvailabilityClusterService = new HighAvailabilityClusterService();
        $this->containerService               = new ContainerService();
    }

    public function handle($text = null)
    {
        $this->initParams();
        $this->initServices();
        $this->initVm();
        if ($this->isDone())
        {
            //Reset IP addresses usage
            if($this->configuration()->isQemu()){
                VmIpAddress::ofHostingId($this->getWhmcsParamByKey('serviceid'))
                    ->ofVmId(sl('Vm')->getVmModel()->id)
                    ->update(['net' => "" ]);
                VirtualInterface::ofHostingId($this->getWhmcsParamByKey('serviceid'))
                    ->ofVmId(sl('Vm')->getVmModel()->id)
                    ->update(['net' => "" ]);
            }
            return true;
        }
        else
        {
            if ($this->isTaskRunning())
            {
                $this->sleep(20);
                return false;
            }
        }
        //Delete HA
        if ($this->highAvailabilityClusterService->exist())
        {
            $this->highAvailabilityClusterService->delete();
        }
        if (sl('Vm')->getVm()->isRunning())
        {
            sl('Vm')->getVm()->stop();
            sleep(15);
        }
        //vm protection
        if (sl('Vm')->getVm()->config()['protection'] == "1")
        {
            sl('Vm')->getVm()->protectionOff();
            sleep(1);
        }
        //vm container
        $this->saveVmContainer();
        //delete vm
        $taskId = sl('Vm')->getVm()->delete();
        //save task id
        $this->putModelDataAndSave(["taskId" => $taskId, "node" => sl('Vm')->getVm()->getNode()]);
        //task history
        $this->createTaskHistory($taskId, "Destroy");
        $this->sleep(10);
        return false;
    }

    private function saveVmContainer()
    {
        if ($this->getModelData()['container'])
        {
            return;
        }
        if ($this->configuration()->isLxc())
        {
            $container               = sl('Vm')->getVm()->getReinstallConfig();
            $container['vmid']       = sl('Vm')->getVm()->getVmid();
            $container['ostemplate'] = $this->getModelData()['osTemplate'];
            $container['password']   = decrypt($this->getModelData()['password']);
            //SSH Public key.
            if ($this->configuration()->isSshKeyPairs())
            {
                $container['ssh-public-keys'] = $this->containerService->makeKeyPairs()->getPublic();
            }
            $this->putModelDataAndSave(['container' => $container]);
        }
    }
}