<?php


namespace ModulesGarden\ProxmoxAddon\App\Jobs\Cloud;


use Illuminate\Database\Capsule\Manager as DB;
use MGProvision\Proxmox\v2\Api;
use MGProvision\Proxmox\v2\models\Features;
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\AdditionalMountPointService;
use ModulesGarden\ProxmoxAddon\App\Services\Cloud\AgentService;
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 CreateLxcJob extends BaseJob
{

    use ProductService;
    use UserService;
    use VmNetwork;

    /**
     * @var ContainerService
     */
    protected $containerService;

    protected function initServices()
    {
        $this->emailService     = new EmailService();
        $this->containerService = new ContainerService();
        $this->agentService = new AgentService();
        $this->additionalMountPointService = new AdditionalMountPointService();

    }

    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->additionalMountPointService->hasMountPoint()){
                $this->additionalMountPointService->create($this->getModelData());
            }
            fire(new VmCreatedEvent($this->getVmModel(), $this->getModelData()));
            return true;
        }
        elseif ($this->isTaskRunning())
        {
            //sleep
            $this->sleep(5);
            return false;
        }
        try
        {
            Api::beginTransaction();
            DB::beginTransaction();
            //vmid
            $vmid = $this->nextVmid();
            $this->getVmModel();
            $this->vmModel->vmid = $vmid;
            sl('Vm')->setVm(null);
            sl('Vm')->setVmModel(   $this->vmModel);
            $container = [
                'vmid'       => $vmid,
                'ostemplate' => $this->getModelData()['osTemplate'],
                'hostname'   => $this->vmModel->name,
                'password'   => $this->vmModel->getPassword(),
            ];
            if($this->getModelData()['osTemplate']=='installationFromArchive'){
                list($backupNode, $volid) = explode(":",  $this->getModelData()['archive'], 2);
                $this->vmModel->node = $backupNode;
                $container['ostemplate'] = $volid;
            }
            $this->vmModel->save();
            //Configurable Options
            if ($this->getVmModel()->cpulimit )
            {
                $container['cpulimit'] = $this->getVmModel()->cpulimit;
            }
            //Memory
            $container['memory'] = $this->getVmModel()->memory;
            //SWAP
            $container['swap'] = $this->getVmModel()->swap;
            //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);
            }
            //cores
            if ($this->getVmModel()->cores)
            {
                $container['cores'] = $this->getVmModel()->cores;
            }
            //arch
            if ($this->configuration()->getArch())
            {
                $container['arch'] = $this->configuration()->getArch();
            }
            //cmode
            if ($this->configuration()->getCmode())
            {
                $container['cmode'] = $this->configuration()->getCmode();
            }
            //console
            if ($this->configuration()->isConsole())
            {
                $container['console'] = 1;
            }
            //description
            if ($this->getModelData()['description'])
            {
                $container['description'] = $this->getModelData()['description'];
            }
            //onboot
            if ($this->configuration()->isOnboot())
            {
                $container['onboot'] = 1;
            }
            //ostype
            if ($this->configuration()->getOsType())
            {
                $container['ostype'] = $this->configuration()->getOsType();
            }
            //pool
            if ($this->configuration()->getPool())
            {
                $container['pool'] = $this->configuration()->getPool();
            }
            //protection
            if ($this->configuration()->isProtection())
            {
                $container['protection'] = 1;
            }
            //startup
            if ($this->configuration()->getStartup())
            {
                $container['startup'] = $this->configuration()->getStartup();
            }
            //storage
            $dafaultStorage  = NodeSetting::ofServer($this->getWhmcsParamByKey('serverid'))
                                           ->ofNode($this->getNode()->getNode())
                                           ->ofSetting('defaultStorage')
                                           ->value("value");
            $container['storage'] = $dafaultStorage ? $dafaultStorage: $this->configuration()->getStorage();
            if($this->getWhmcsConfigOption(ConfigurableOption::STORAGE_DISK)){
                list($storage,$diskSize) = explode(":", $this->getWhmcsConfigOption(ConfigurableOption::STORAGE_DISK),2);
                $container['storage'] = $storage;
            }
            //tty
            if ($this->configuration()->getTty())
            {
                $container['tty'] = $this->configuration()->getTty();
            }
            //unprivileged
            $container['unprivileged'] = $this->configuration()->isUnprivileged() ? 1 : 0;
            //Disk
            $diskSize = $this->getVmModel()->disk;
            //Rootfs
            $container['rootfs'] = "{$container['storage']}:{$diskSize}";
            //SSH Public key.
            if ($this->configuration()->isSshKeyPairs())
            {
                $keyPairs =  $this->containerService->makeKeyPairs();
                $keyPairs->vm_id = $this->getVmModel()->id;
                $keyPairs->save();
                $container['ssh-public-keys'] = $keyPairs->getPublic();
            }
            //Network
            $networkService = new NetworkService();
            $container      += $this->createNetwork();
            //start
            if ($this->configuration()->isStart()  && version_compare($this->api()->getVersion(), "4.4", '>'))
            {
                $container['start'] = 1;
            }
            //features
            $features = new Features();
            //Keyctl
            if($this->configuration()->isFeatureKeyctl() && $this->configuration()->isUnprivileged()){
                $features->setKeyctl(1);
            }
            //Nesting
            if($this->configuration()->isFeatureNesting() ){
                $features->setNesting(1);
            }
            //NFS
            if($this->configuration()->isFeatureNfs() ){
                $features->addNfs();
            }
            //CIFS
            if($this->configuration()->isFeatureCifs() ){
                $features->addCifs();
            }
            //Fuse
            if($this->configuration()->isFeatureFuse() ){
                $features->setFuse(1);
            }
            //Mknod
            if($this->configuration()->isFeatureMknod() ){
                $features->setMknod(1);
            }
            if(!$features->isEmpty()){
                $container[Features::ID] = $features->asConfig();
            }

            //Create
            $vm          =  (new VmFactory())->fromVmModel($this->getVmModel());
            $taskId = $vm->create($container);
            DB::commit();
        }
        catch (\Exception $ex)
        {
            DB::rollBack();
            Api::commit();
            $this->failed($ex->getMessage());
            throw $ex;
        }
        //task history
        $this->createTaskHistory($taskId, "Create");
        //save task id
        $this->putModelDataAndSave(["taskId" => $taskId, "node" => $this->getVmModel()->node]);
        //sleep
        $this->sleep();
        return false;

    }


}
