<?php

namespace ModulesGarden\Servers\ProxmoxCloudVps\App\UI\VmUpdate\Providers;


use Illuminate\Database\Capsule\Manager as DB;
use MGProvision\Proxmox\v2\Api;
use MGProvision\Proxmox\v2\models\Kvm;
use MGProvision\Proxmox\v2\models\MountPoint;
use MGProvision\Proxmox\v2\models\NetworkDeviceKvm;
use MGProvision\Proxmox\v2\repository\FileRepository;
use MGProvision\Proxmox\v2\repository\StorageRepository;
use ModulesGarden\ProxmoxAddon\App\Events\Cloud\LxcUpdateEvent;
use ModulesGarden\ProxmoxAddon\App\Events\Cloud\QemuUpdateEvent;
use ModulesGarden\ProxmoxAddon\App\Jobs\Cloud\Agent\ChangePasswordJob;
use ModulesGarden\ProxmoxAddon\App\Jobs\Cloud\Agent\ConfigureNetworkJob;
use ModulesGarden\ProxmoxAddon\App\Models\VirtualInterface;
use ModulesGarden\ProxmoxAddon\App\Models\VmIpAddress;
use ModulesGarden\ProxmoxAddon\App\Models\VmModel;
use ModulesGarden\ProxmoxAddon\App\Services\ApiService;
use ModulesGarden\ProxmoxAddon\App\Services\Cloud\AdditionalDiskService;
use ModulesGarden\ProxmoxAddon\App\Services\Cloud\AdditionalMountPointService;
use ModulesGarden\ProxmoxAddon\App\Services\Cloud\AgentService;
use ModulesGarden\ProxmoxAddon\App\Services\Cloud\IpSetIpFilterService;
use ModulesGarden\ProxmoxAddon\App\Services\Cloud\NetworkService;
use ModulesGarden\ProxmoxAddon\App\Services\Cloud\ProductService;
use ModulesGarden\ProxmoxAddon\App\Services\Cloud\VirtualInterfaceConverter;
use ModulesGarden\Servers\ProxmoxCloudVps\App\UI\VmCreate\Providers\VmCreateProvider;
use ModulesGarden\Servers\ProxmoxCloudVps\Core\UI\ResponseTemplates\HtmlDataJsonResponse;
use function ModulesGarden\ProxmoxAddon\Core\Helper\fire;
use function ModulesGarden\ProxmoxAddon\Core\Helper\queue;
use function ModulesGarden\Servers\ProxmoxCloudVps\Core\Helper\sl;

class VmUpdateProvider extends VmCreateProvider
{
    use ApiService;
    use ProductService;


    /**
     * VmUpdateProvider constructor.
     */
    public function __construct()
    {
        $this->model = VmModel::class;
    }


    public function read()
    {
        $this->vmModel = \ModulesGarden\ProxmoxAddon\Core\Helper\sl('Vm')->getVmModel();
        $this->data =  $this->vmModel->toArray();
        $vm = \ModulesGarden\ProxmoxAddon\Core\Helper\sl('Vm')->getVm();
        $config = $vm->config();
        $this->data['ciuser'] = $config['ciuser'];
        $this->data['cipassword'] = $config['cipassword'];
        $this->data['description'] = html_entity_decode($config['description']);
        $this->data['searchdomain'] = $config['searchdomain'];
        $ns = explode(" ",$config['nameserver']);
        $this->data['nameserver[0]'] = $ns[0];
        $this->data['nameserver[1]'] = $ns[1];
        /**
         * @deprecated
        $this->data['ipv4'] = $this->vmModel->ipv4Addresses->count();
        $this->data['ipv6'] = $this->vmModel->ipv6Addresses->count();
         */
        //sshkeys
        $this->data['sshkeys'] = rawurldecode($vm->config()['sshkeys']);
        //cpu Priority
        if($this->configuration()->hasCpuPriority()){
            for($i=1; $i<=5; $i++){
                $cpuunits = $this->configuration()->get('cpuunitsPriority'.$i);
                $cpulimit = $this->configuration()->get('cpulimitPriority'.$i);
                if($this->vmModel->cpulimit >= $cpulimit){
                    $this->data['cpuPriority'] = $i;
                }
                if($this->vmModel->cpuunits >= $cpuunits){
                    $this->data['cpuPriority'] = $i;
                }
            }
        }
        //iso
        if ($this->configuration()->isQemu() && $this->configuration()->isPermissionIsoImage()) {
            $this->availableValues['iso'] = ["none" => sl('lang')->abtr("None")];
            $storageRepository = new StorageRepository();
            $storageRepository->findByNodes([$vm->getNode()])
                ->findEnabed();
            $storages = $storageRepository->fetchAsArray();
            $isoRepository = new FileRepository();
            $isoRepository->findByNodes([$vm->getNode()])
                ->findByStorages($storages);
            $isoRepository->findIso();
            foreach ($isoRepository->fetch() as $entity) {
                if ($this->configuration()->isPermissionIsoImages() && !in_array($entity->getVolid(), $this->configuration()->getPermissionIsoImages())) {
                    continue;
                }
                $this->availableValues['iso'][$entity->getVolid()] = $entity->getFriendlyName();
            }
            if( $vm->getCdRomRepository()->first()){
                $this->data['iso']= $vm->getCdRomRepository()->first()->getLocation();
            }
        }



    }

    public function update()
    {
        $this->vmModel = \ModulesGarden\ProxmoxAddon\Core\Helper\sl('Vm')->getVmModel();
        $vm = \ModulesGarden\ProxmoxAddon\Core\Helper\sl('Vm')->getVm();
        $this->networkService = new NetworkService();
        $networkService = new NetworkService();
        /**
         * @deprecated
         * $ipv4 = (int) $this->formData['ipv4'] - (int)  $this->vmModel->ipv4Addresses->count();
         * $ipv6  = (int) $this->formData['ipv6'] - (int)  $this->vmModel->ipv6Addresses->count();
         * $networkService->hasIp($ipv4, $ipv6, $this->vmModel->node);
         * $networkService->addIp($ipv4, $ipv6, $this->vmModel->node);
         * $networkService->unassignIpAddressesAndDeleteNetwork($ipv4, $ipv6);
         */

        //load data
        $this->getFormDataValues();
        if ($vm instanceof Kvm)
        {
            //iso
            if ($vm->cdrom())
            {
                $vm->updateCdrom($this->formData['iso']);
            }
            //sshkeys
            if($this->configuration()->isPermissionSshkeys()){
                if ($this->formData['sshkeys'])
                {
                    $vm->updateConfig(["sshkeys" => rawurlencode($this->formData['sshkeys'])]);
                } else if($vm->config()['sshkeys'])
                {
                    $vm->deleteConfig('sshkeys');
                }
            }
        }
        try{
            Api::beginTransaction();
            DB::beginTransaction();
            $this->fillVmModel();
            if($this->getFormDataValues()['ciuser']){
                $vm->updateConfig(["ciuser" => $this->formData['ciuser']]);
            }
            if($this->getFormDataValues()['cipassword']){
                $vm->updateConfig(["cipassword" => $this->formData['cipassword']]);
            }
            if($this->configuration()->isCalculateSocketsAndCores()){
                $this->calculateSocketsAndCores();
            }
            $this->vmModel->save();
            if($this->configuration()->isQemu()){
                fire(new QemuUpdateEvent($this->vmModel, $this->formData));
            }
            if($this->configuration()->isLxc()){
                fire(new LxcUpdateEvent($this->vmModel, $this->formData));
            }
            $agentEnabled = (new AgentService())->isEnabled();
            if($agentEnabled && $this->configuration()->isAgentConfigureNetwork()){
                queue(ConfigureNetworkJob::class,
                    ['hostingId' => $this->getWhmcsParamByKey('serviceid')],
                    null,
                    "hosting",
                    $this->getWhmcsParamByKey("serviceid"),
                    $this->vmModel->id
                );
            }
            if($agentEnabled && $this->configuration()->isAgentPassword()){
                queue(ChangePasswordJob::class,
                    ['hostingId' => $this->getWhmcsParamByKey('serviceid')],
                    null,
                    "hosting",
                    $this->getWhmcsParamByKey("serviceid"),
                    $this->vmModel->id
                );
            }
            DB::commit();
            return (new  HtmlDataJsonResponse())
                ->setMessageAndTranslate('Server has been updated')
                ->setCallBackFunction('pcVmUpdatedAjaxDone')
                ->addRefreshTargetId('serviceInformationDataTable')
                ->setCallBackFunction('mgLocationReload');
        }catch (\Exception $ex){
            DB::rollBack();
            Api::commit();
            return (new  HtmlDataJsonResponse())
                ->setStatusError()
                ->setMessageAndTranslate($ex->getMessage());
        }

    }
}