<?php


namespace ModulesGarden\ProxmoxAddon\App\Jobs\Cloud;


use Illuminate\Database\Capsule\Manager as DB;
use MGProvision\Proxmox\v2\Api;
use MGProvision\Proxmox\v2\models\HardDisk;
use MGProvision\Proxmox\v2\models\Node;
use MGProvision\Proxmox\v2\VmFactory;
use ModulesGarden\ProxmoxAddon\App\Enum\Cloud\ConfigurableOption;
use ModulesGarden\ProxmoxAddon\App\Events\Cloud\VmCreatedEvent;
use ModulesGarden\ProxmoxAddon\App\Jobs\BaseJob;
use ModulesGarden\ProxmoxAddon\App\Models\NodeSetting;
use ModulesGarden\ProxmoxAddon\App\Services\Cloud\AdditionalDiskService;
use ModulesGarden\ProxmoxAddon\App\Services\Cloud\ContainerService;
use ModulesGarden\ProxmoxAddon\App\Services\Cloud\NetworkService;
use ModulesGarden\ProxmoxAddon\App\Services\Cloud\ProductService;
use ModulesGarden\ProxmoxAddon\App\Services\Cloud\UserService;
use ModulesGarden\ProxmoxAddon\App\Services\EmailService;
use ModulesGarden\ProxmoxAddon\App\Traits\Cloud\VmNetwork;
use function ModulesGarden\ProxmoxAddon\Core\Helper\fire;
use function ModulesGarden\ProxmoxAddon\Core\Helper\sl;

class CreateQemuJob extends BaseJob
{
    use ProductService;
    use UserService;
    use VmNetwork;


    /**
     * @var NetworkService
     */
    protected $networkService;

    protected function initServices()
    {
        $this->emailService     = new EmailService();
        $this->containerService = new ContainerService();
        $this->networkService   = new NetworkService();
        $this->additionalDiskService = new AdditionalDiskService();
    }

    public function handle()
    {
        $this->initParams();
        $this->initServices();
        $this->setHostingId($this->getWhmcsParamByKey("serviceid"));
        //create task validation
        if ($this->isDone())
        {
            $this->initVm();
            if($this->getModelData()['additionalDiskSize1'] && !$this->additionalDiskService->hasDisk()){
                $this->additionalDiskService->create($this->getModelData());
            }
            fire(new VmCreatedEvent($this->getVmModel()));
            return true;
        }
        elseif ($this->isTaskRunning())
        {
            //sleep
            $this->sleep(5);
            return false;
        }
        try
        {
            Api::beginTransaction();
            DB::beginTransaction();
            //vmid
            $vmid = $this->nextVmid();
            $vmModel =    $this->getVmModel();
            $vmModel->vmid = $vmid;
            $vmModel->save();
            sl('Vm')->setVm(null);
            sl('Vm')->setVmModel( $vmModel);
            $container = [
                'vmid'   => $vmid,
                'name'   =>  $this->getVmModel()->name,
                "ostype" =>  $this->getModelData()['ostype'] ? $this->getModelData()['ostype'] : $this->configuration()->getOsType(),
            ];
            //vcpus
            if ($this->getVmModel()->vcpus)
            {
                $container['vcpus'] = $this->getVmModel()->vcpus ;
            }
            //cpulimit
            if ($this->getVmModel()->cpulimit)
            {
                $container['cpulimit'] = $this->getVmModel()->cpulimit;
            }
            // Boot order device
            if ($this->configuration()->getBootOrder())
            {
                $container['boot'] = $this->configuration()->getBootOrder();
            }
            //numa
            if ($this->configuration()->isNuma())
            {
                $container['numa'] = 1;
            }
            //Memory
            if ($this->getVmModel()->memory)
            {
                $container['memory'] = $this->getVmModel()->memory;
            }
            //cpuunits
            if ($this->getVmModel()->cpuunits)
            {
                $container['cpuunits'] = $this->getVmModel()->cpuunits;
            }
            //Name servers
            $ns = [];
            for ($i = 0; $i <= 1; $i++)
            {
                $n = trim($this->getModelData()['nameserver'][$i]);
                if (!empty($n) && !filter_var($n, FILTER_VALIDATE_IP))
                {
                    $n = gethostbyname($n);
                }
                if (!empty($n) && filter_var($n, FILTER_VALIDATE_IP))
                {
                    $ns[] = $n;
                }
            }
            if ($ns)
            {
                $container['nameserver'] = implode(" ", $ns);
            }
            //sockets
            if ($this->getVmModel()->sockets)
            {
                $container['sockets'] = $this->getVmModel()->sockets;
            }
            //cores
            if ($this->getVmModel()->cores)
            {
                $container['cores'] = $this->getVmModel()->cores;
            }
            //description
            if ($this->getModelData()['description'])
            {
                $container['description'] = $this->getModelData()['description'];
            }
            //onboot
            if ($this->configuration()->isOnboot())
            {
                $container['onboot'] = 1;
            }
            //pool
            if ($this->configuration()->getPool())
            {
                $container['pool'] = $this->configuration()->getPool();
            }
            //startup
            if ($this->configuration()->getStartup())
            {
                $container['startup'] = $this->configuration()->getStartup();
            }
            //busDevces
            $busDevices = [
                "ide"    => 0,
                "sata"   => 0,
                "virtio" => 0,
                "scsi"   => 0
            ];
            if (!$this->configuration()->getCdromType())
            {
                throw new \InvalidArgumentException("CD-ROM Type is empty, product configuration is not valid");
            }
            //CD-ROM primary ISO
            $type = $this->configuration()->getCdromType();
            $bus  = $busDevices[$type];
            $busDevices[$type]++;
            $isoImage =  $this->getModelData()['isoImage'] ? $this->getModelData()['isoImage'] : "none";
            $container[$type . $bus] = "{$isoImage},media=cdrom";
            //secondaryIsoImage
            if($this->getModelData()['secondaryIsoImage']){
                $bus  = $busDevices[$type];
                $busDevices[$type]++;
                $container[$type . $bus] = "{$this->getModelData()['secondaryIsoImage']},media=cdrom";
            }
            //Disk
            $diskSize = $this->getVmModel()->disk;
            $type = $this->configuration()->getDiskType();
            $bus  = $busDevices[$type];
            $busDevices[$type]++;
            $harDisk = new HardDisk($type . $bus);
            $dafaultStorage  = NodeSetting::ofServer($this->getWhmcsParamByKey('serverid'))
                                           ->ofNode($this->getNode()->getNode())
                                           ->ofSetting('defaultStorage')
                                           ->value("value");
            $harDisk->setSize($diskSize)
                ->setStorage($dafaultStorage ? $dafaultStorage : $this->configuration()->getDiskStorage())
                ->setCache($this->configuration()->getDiskCache())
                ->setFormat($this->configuration()->getDiskFormat())
                ->setMbps_rd($this->configuration()->getMbpsRd())
                ->setMbps_wr($this->configuration()->getMbpsWr())
                ->setDiscard($this->configuration()->isDiscard() ? "on" : null)
                ->setIops_rd($this->configuration()->getIopsRd())
                ->setIops_rd_max($this->configuration()->getIopsRdMax())
                ->setIops_wr($this->configuration()->getIopsWr())
                ->setIops_wr_max($this->configuration()->getIopsWrMax())
                ->setReplicate($this->configuration()->isReplicate() ? 0 : null)
                ->setSsd($this->configuration()->isSsd() ? 1 : null);
            if($this->getWhmcsConfigOption(ConfigurableOption::STORAGE_DISK)){
                list($storage,$diskSize) = explode(":", $this->getWhmcsConfigOption(ConfigurableOption::STORAGE_DISK),2);
                $harDisk->setStorage($storage);
            }
            if ($this->configuration()->isIoThread() && in_array($type, ['virtio', 'scsi']))
            {
                $harDisk->setIothread($this->configuration()->isIoThread());
            }
            $container[$harDisk->getId()] = $harDisk->asConfig();
            //Network
            $container += $this->createNetwork();
            //acpi
            if ($this->configuration()->isAcpi())
            {
                $container['acpi'] = 1;
            }
            //agent
            if ($this->configuration()->isAgent())
            {
                $container['agent'] = 1;
            }
            //autostart
            if ($this->configuration()->isAutostart())
            {
                $container['autostart'] = 1;
            }
            //balloon
            if ($this->configuration()->getBalloon())
            {
                $container['balloon'] = $this->configuration()->getBalloon();
            }
            //shares
            if ($this->configuration()->getShares())
            {
                $container['shares'] = $this->configuration()->getShares();
            }
            //cdrom
            if ($this->configuration()->getCdrom())
            {
                $container['cdrom'] = $this->configuration()->getCdrom();
            }
            //cpu
            if ($this->configuration()->getCpu())
            {
                $container['cpu'] = $this->configuration()->getCpu();
            }
            //freeze
            if ($this->configuration()->isFreeze())
            {
                $container['freeze'] = 1;
            }
            //hotplug
            if ($this->configuration()->getHotplug())
            {
                $container['hotplug'] = $this->configuration()->getHotplug();
            }
            //keyboard
            if ($this->configuration()->getKeyboard())
            {
                $container['keyboard'] = $this->configuration()->getKeyboard();
            }
            //kvm
            if ($this->configuration()->isKvm())
            {
                $container['kvm'] = 1;
            }
            //localtime
            if ($this->configuration()->isLocaltime())
            {
                $container['localtime'] = 1;
            }
            //migrate_downtime
            if ($this->configuration()->getMigrateDowntime())
            {
                $container['migrate_downtime'] = $this->configuration()->getMigrateDowntime();
            }
            //migrate_speed
            if ($this->configuration()->getMigrateSpeed())
            {
                $container['migrate_speed'] = $this->configuration()->getMigrateSpeed();
            }
            //reboot
            if ($this->configuration()->isReboot())
            {
                $container['reboot'] = 1;
            }
            //startdate
            if ($this->configuration()->getStartdate())
            {
                $container['startdate'] = $this->configuration()->getStartdate();
            }
            //startup
            if ($this->configuration()->getStartup())
            {
                $container['startup'] = $this->configuration()->getStartup();
            }
            //tablet
            if ($this->configuration()->isTablet())
            {
                $container['tablet'] = 1;
            }
            //tdf
            if ($this->configuration()->isTdf())
            {
                $container['tdf'] = 1;
            }
            //watchdog
            if ($this->configuration()->getWatchdog())
            {
                $container['watchdog'] = $this->configuration()->getWatchdog();
            }
            //bootdisk
            if ($this->configuration()->getBootdisk())
            {
                $container['bootdisk'] = $this->configuration()->getBootdisk();
            }
            //scsihw
            if ($this->configuration()->getScsihw())
            {
                $container['scsihw'] = $this->configuration()->getScsihw();
            }
            //args
            if ($this->configuration()->getArgs())
            {
                $container['args'] = $this->configuration()->getArgs();
            }
            //vga
            $vga=[];
            if ($this->configuration()->getVga())
            {
                $vga[] = $this->configuration()->getVga();
            }
            if($container['vga']!="none" && $this->configuration()->getVgaMemory()){
                $vga[]="memory=".$this->configuration()->getVgaMemory();
            }
            if(!empty($vga)){
                $container['vga'] = implode(",",$vga);
            }
            //xterm.js Console
            if ($this->configuration()->isPermissionXtermjs())
            {
                $container['serial0'] = 'socket';
            }
            //cpu flags

            if ($this->configuration()->hasCpuFlags()  && version_compare($this->api()->getVersion(), "5.2", '>'))
            {
                $container['cpu'] .= ',flags=' .$this->configuration()->getCpuFlagsAsSource();
            }
            //start
            if ($this->configuration()->isStart())
            {
                $container['start'] = 1;
            }
            //bios
            if ($this->configuration()->getBios())
            {
                $container['bios'] = $this->configuration()->getBios();
            }
            //machine
            if ($this->configuration()->getMachine())
            {
                $container['machine'] = $this->configuration()->getMachine();
            }
            //Create
            $nodeService = new Node($this->getVmModel()->node);
            $vm          = $nodeService->kvm();
            $this->setVm($vm);
            $vm = (new VmFactory())->fromVmModel( $vmModel);
            //init vm
            sl('Vm')->setVm($vm);
            $taskId = $vm->create($container);
            DB::commit();
        }
        catch (\Exception $ex)
        {
            echo $ex->getMessage();
            DB::rollBack();
            Api::commit();
            throw $ex;
        }
        //task history
        $this->createTaskHistory($taskId, "Create");
        //save task id
        $this->putModelDataAndSave(["taskId" => $taskId, "node" => $nodeService->getNode()]);
        //sleep
        $this->sleep();
        return false;
    }




}
