<?php

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

use ModulesGarden\ProxmoxAddon\App\Jobs\Vps\BaseJob;
use ModulesGarden\ProxmoxAddon\App\Services\Vps\ContainerService;
use ModulesGarden\ProxmoxAddon\App\Services\Vps\HighAvailabilityClusterService;
use ModulesGarden\ProxmoxAddon\App\Services\Vps\ProductService;

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();
        if ($this->isDone())
        {
            return true;
        }
        else
        {
            if ($this->isTaskRunning())
            {
                $this->sleep(20);
                return false;
            }
        }
        //Delete HA
        if ($this->highAvailabilityClusterService->exist())
        {
            $this->highAvailabilityClusterService->delete();
        }
        if ($this->vm()->isRunning())
        {
            $this->vm()->stop();
            sleep(15);
        }
        //vm protection
        if ($this->vm()->config()['protection'] == "1")
        {
            $this->vm()->protectionOff();
            sleep(1);
        }
        //vm container
        $this->saveVmContainer();
        //delete vm
        $taskId = $this->vm()->delete();
        //save task id
        $this->putModelDataAndSave(["taskId" => $taskId, "node" => $this->vm()->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               = $this->vm()->getReinstallConfig();
            $container['vmid']       = $this->vm()->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]);
        }
    }
}