<?php

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


use MGProvision\Proxmox\v2\models\Kvm;
use ModulesGarden\ProxmoxAddon\App\Jobs\Cloud\CloneQemuJob;
use ModulesGarden\ProxmoxAddon\App\Jobs\Cloud\CreateLxcJob;
use ModulesGarden\ProxmoxAddon\App\Jobs\Cloud\CreateQemuJob;
use ModulesGarden\ProxmoxAddon\App\Jobs\Cloud\CreateSnippet;
use ModulesGarden\ProxmoxAddon\App\Libs\Format;
use ModulesGarden\ProxmoxAddon\App\Models\CloudInitScript;
use ModulesGarden\ProxmoxAddon\App\Models\VirtualInterface;
use ModulesGarden\ProxmoxAddon\App\Models\VirtualNetwork;
use ModulesGarden\ProxmoxAddon\App\Models\VmIpAddress;
use ModulesGarden\ProxmoxAddon\App\Models\VmModel;
use ModulesGarden\ProxmoxAddon\App\Services\ApiService;
use ModulesGarden\ProxmoxAddon\App\Services\Cloud\NetworkService;
use ModulesGarden\ProxmoxAddon\App\Services\Cloud\ProductService;
use ModulesGarden\ProxmoxAddon\App\Services\Cloud\ResourceManager;
use ModulesGarden\ProxmoxAddon\App\Services\Ip\Ipv4Range;
use ModulesGarden\ProxmoxAddon\App\Services\Utility;
use ModulesGarden\Servers\ProxmoxCloudVps\App\Helpers\BuildUrl;
use ModulesGarden\Servers\ProxmoxCloudVps\App\Helpers\UrlServiceHelper;
use ModulesGarden\Servers\ProxmoxCloudVps\Core\FileReader\Reader\Json;
use ModulesGarden\Servers\ProxmoxCloudVps\Core\ModuleConstants;
use ModulesGarden\Servers\ProxmoxCloudVps\Core\UI\Interfaces\ClientArea;
use ModulesGarden\Servers\ProxmoxCloudVps\Core\UI\ResponseTemplates\HtmlDataJsonResponse;
use ModulesGarden\Servers\ProxmoxCloudVps\Core\UI\Widget\Forms\DataProviders\BaseModelDataProvider;
use function ModulesGarden\Servers\ProxmoxCloudVps\Core\Helper\queue;
use function ModulesGarden\Servers\ProxmoxCloudVps\Core\Helper\sl;

class VmCreateProvider extends BaseModelDataProvider implements ClientArea
{
    use ApiService;
    use ProductService;


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


    public function read()
    {
         parent::read();
        /**
         * virtual network ip addresses
         * @deprecated
        foreach (VirtualNetwork::ofHostingId($this->getWhmcsParamByKey('serviceid'))->get() as $vn){
            $ipRange = new Ipv4Range($vn->pool, $vn->cidr);
            $ipRange->setLimit(10);
            $ipRange->disableIpAddresses( $vn->virtualInterfaces->pluck('ip')->toArray());
            $this->availableValues[sprintf("ip[%s]", $vn->id)] [0] = sl('lang')->abtr('None');
            foreach (  $ipRange->get() as $ip ){
                $this->availableValues[sprintf("ip[%s]", $vn->id)] [$ip] = $ip;
            }
        }
         */
        //location
        foreach ($this->configuration()->getLocations() as $location){
            $this->availableValues['location'] [$location] = sl('lang')->abtr('location', $location);
        }
        //ostype
        $osTypes = $this->configuration()->getPermissionOstype();
        if($osTypes){
            $ostype = new Json('ostype.json', ModuleConstants::getFullPathWhmcs('modules', 'addons', 'proxmoxAddon', 'storage', 'app'));
            foreach ($ostype->get() as $k => $ostype)
            {
                if(!in_array($k, $osTypes)){
                    continue;
                }
                $this->availableValues["ostype"][$k] = sl('lang')->abtr('ostype',$ostype);
            }
        }
        //cloudInitScript
        if($this->configuration()->getCloudInitScript()){
            $this->availableValues["cloudInitScript"] = CloudInitScript::ofIds($this->configuration()->getCloudInitScript())
                      ->orderBy('name','asc')
                      ->pluck('name','id')
                      ->prepend(sl('lang')->abtr('None'),0)
                      ->toArray();
        }
    }

    public function create()
    {
        //Clone KVM check disk size
        if($this->getJobClass() == CloneQemuJob::class && !$this->isDiskSizeValid()){
            sl("lang")->addReplacementConstant("size", Format::convertBytes($this->vmTemplate->getMasterHardDisk()->getBytes()));
            return (new HtmlDataJsonResponse())
                ->setStatusError()
                ->setMessageAndTranslate('OS Template require disk size :size:');
        }
        $resurceManager = new ResourceManager();
        //disk size validation
        $diskResource =   $resurceManager ->disk();
        $diskResource->setTotal($diskResource ->getTotal() - $this->formData['disk']);
        $additonalDiskSize = $this->getAdditionalDiskTotalSize();
        if($additonalDiskSize && $additonalDiskSize > $diskResource->freeTotal() ){
            sl("lang")->addReplacementConstant("additional_disks_size",  $additonalDiskSize);
            sl("lang")->addReplacementConstant("size", $diskResource->freeTotal());
            return (new HtmlDataJsonResponse())
                ->setStatusError()
                ->setMessageAndTranslate('You are not able to set :additional_disks_size: GB of the additional disks size. The available size is: :size: GB');
        }
        //ipv4
        if($this->configuration()->serverIpv4->min &&  $this->configuration()->serverIpv4->min > $this->countPublicIpv4() ){
            return (new HtmlDataJsonResponse())
                ->setStatusError()
                ->setMessageAndTranslate('Select the Virtual Network with IPv4 address');
        }
        $this->vmModel = new VmModel();
        $this->fillVmModel();
        if($this->vmTemplate instanceof  Kvm){
            $this->vmModel->data = ['osTemplate'=> $this->vmTemplate->status()['name']];
        }else{
            $this->vmModel->data = ['osTemplate'=> $this->formData['osTemplate']];
        }
        $this->vmModel->setPassword($this->formData['password']);
        $this->vmModel->hosting_id = $this->getWhmcsParamByKey('serviceid');
        unset($this->formData['password']);
        $this->vmModel->virtualization = $this->configuration()->getVirtualization();
        if($this->formData['location'] && in_array($this->formData['location'], $this->configuration()->getLocations())){
            $this->vmModel->node = $this->formData['location'];
        }else{
            $this->vmModel->node = $this->getNode()->getNode();
        }
        if($this->configuration()->isCalculateSocketsAndCores()){
            $this->calculateSocketsAndCores();
        };
        //init vm
        $this->vmModel->save();
        \ModulesGarden\ProxmoxAddon\Core\Helper\sl('Vm')->setVmModel($this->vmModel);
        $this->createJob();
        //virtual interfaces
        for($i=1; $i<=20; $i++){
            if(!$this->formData['virtualNetwork'.$i]){
                continue;
            }
            $ip = $this->formData['virtualNetwork'.$i]['ip'];
            $virtualNetworkId = $this->formData['virtualNetwork'.$i]['id'];
            //lock public ip
            if(  $virtualNetworkId == 'public'){
                VmIpAddress::ofHostingId($this->getWhmcsParamByKey('serviceid'))
                    ->ofIp($ip)
                    ->update(['vm_id' => $this->vmModel->id ]);
            }
            $vi = new VirtualInterface();
            $vi->ip = $ip;
            $vi->ip_long = ip2long($ip);
            $vi->vm_id = $this->vmModel->id;
            $vi->vn_id = $virtualNetworkId=="public"? 0 : $virtualNetworkId;
            $vi->hosting_id = $this->getWhmcsParamByKey('serviceid');
            $vi->save();
        }

        /**
         * @deprecated
         $networkService = new NetworkService();
        //ip validation
        $networkService->hasIp((int)$this->formData['ipv4'], (int)$this->formData['ipv6'], $this->vmModel->node);
        //assign IPs
        $networkService->addIp((int)$this->formData['ipv4'], (int)$this->formData['ipv6'], $this->vmModel->node);
        foreach ($this->formData['ip'] as $virtualNetworkId =>  $ip){
            if($ip == 0){
                continue;
            }
            //request validation
            if(!VirtualNetwork::where('id', $virtualNetworkId)
                ->ofHostingId($this->getWhmcsParamByKey('serviceid'))->count()){
                throw new \InvalidArgumentException(sprintf("Virtual Network %s cannot be found", $virtualNetworkId));
            }
        }
         */
        return (new  HtmlDataJsonResponse())
            ->setMessageAndTranslate('The process of Virtual Machine creation is in progress')
            ->setCallBackFunction('pcVmCreatedAjaxDone')
            ->addData('redirectUrl' , (new UrlServiceHelper())->home());

    }

    private function getJobClass(){
        if($this->getFormDataValues()['osTemplate']  && $this->formData['osTemplate'] !='installationFromIso' && $this->configuration()->isQemu()){
            return CloneQemuJob::class;
        }elseif (  $this->configuration()->isQemu()){
            return CreateQemuJob::class;
        }else{
            return CreateLxcJob::class;
        }

    }

    protected function  getJobArguments(){
        $arguments = $this->formData;
        $arguments['hostingId'] =$this->getWhmcsParamByKey('serviceid');
        return $arguments;
    }

    private function createJob(){
        $jobClass = $this->getJobClass();
        if($jobClass == CloneQemuJob::class  && $this->getFormDataValues()['cloudInitScript']){
            $parent = queue(
                CreateSnippet::class,
                $this->getJobArguments(),
                null,
                "hosting",
                $this->getWhmcsParamByKey("serviceid"),
                $this->vmModel->id
            );
        }
        return queue(
            $this->getJobClass(),
            $this->getJobArguments(),
            $parent->id,
            "hosting",
            $this->getWhmcsParamByKey("serviceid"),
            $this->vmModel->id
        );
    }


    /**
     * @deprecated
     */
    protected function requestValidation(){
        //load form data
        $this->getFormDataValues();
        //ipv4
        if(!$this->configuration()->isPermissionIpv4()){
            $this->formData['ipv4'] = $this->configuration()->serverIpv4->min;
        }
        //ipv6
        if(!$this->configuration()->isPermissionIpv6){
            $this->formData['ipv6'] = $this->configuration()->serverIpv6->min;
        }
    }

    private function isDiskSizeValid(){
        list($node, $vmid) = explode("/", $this->formData['osTemplate']);
        $this->vmTemplate = new Kvm($node, $vmid);
        $this->vmTemplate->setApi($this->api());
        $diskSizeBytes = $this->formData['disk'];
        Utility::unitFormat($diskSizeBytes,'gb','bytes');
        $this->templateDiskSizeBytes = $this->vmTemplate->getMasterHardDisk()->getBytes();
        return $diskSizeBytes >= $this->templateDiskSizeBytes;
    }

    protected function fillVmModel(){
        $this->vmModel->fill($this->getFormDataValues());
        //sockets
        if( !$this->configuration()->isPermissionSockets()  && !$this->configuration()->isCalculateSocketsAndCores()){
            $this->vmModel->sockets = $this->configuration()->serverSockets->min;
        }
        //cores
        if( !$this->configuration()->isPermissionCores() && !$this->configuration()->isCalculateSocketsAndCores() ){
            $this->vmModel->cores = $this->configuration()->serverCores->min;
        }
        //vcpus
        if( !$this->configuration()->isPermissionVcpus() ){
            $this->vmModel->vcpus = $this->configuration()->serverVcpus->min;
        }
        if($this->configuration()->isCalculateSocketsAndCores()){

        }
        //cpulimit
        if( !$this->configuration()->isPermissionCpuLimit() && !$this->formData['cpuPriority']){
//            $this->vmModel->cpulimit = $this->configuration()->serverCpulimit->min;
            $this->vmModel->cpulimit = $this->formData['vcpu'] * 0.8;
        }
        //cpuunits
        if( !$this->configuration()->isPermissionCpuunits() && !$this->formData['cpuPriority']){
            $this->vmModel->cpuunits = $this->configuration()->serverCpuunit->min;
        }
        //swap
        if( !$this->configuration()->isPermissionSwap() ){
            $this->vmModel->swap = $this->configuration()->serverSwap->min;
        }
        //disks
        $disks = (int) $this->getAdditionalDiskTotalSize();
        if($disks || $this->configuration()->isDetailsCombinedView()){
            $this->vmModel->disks = $disks;
        }
        //cpu prioryty
        if($this->formData['cpuPriority']){
            $this->vmModel->cpulimit = $this->configuration()->get('cpulimitPriority'.$this->formData['cpuPriority']);
            $this->vmModel->cpuunits = $this->configuration()->get('cpuunitsPriority'.$this->formData['cpuPriority']);
        }
    }

    private function getAdditionalDiskTotalSize()
    {
        $size = 0;
        for ($i = 1; $i <= 10; $i++) {
            $size += (int)$this->formData['additionalDiskSize' . $i];
        }
        return $size;
    }

    protected function calculateSocketsAndCores()
    {
        $cores =1;
        $socket = 1;
        $cpus = $this->configuration()->serverCores->max;
        while($cpus > 0)
        {
            if($this->vmModel->vcpus % $cpus === 0 && $this->vmModel->vcpus / $cpus <= $this->configuration()->serverSockets->max)
            {
                $cores = $cpus;
                $socket = $this->vmModel->vcpus / $cpus;
            }
            $cpus--;
        }
        $this->vmModel->cores =  $cores;
        $this->vmModel->sockets = $socket;
    }

    public function countPublicIpv4(){
        $total=0;
        for($i=1; $i<=20; $i++){
            if(!$this->formData['virtualNetwork'.$i]){
                continue;
            }
            $ip = $this->formData['virtualNetwork'.$i]['ip'];
            $virtualNetworkId = $this->formData['virtualNetwork'.$i]['id'];
            //lock public ip
            if($ip && !preg_match("/\:/", $ip) &&  $virtualNetworkId == 'public'){

                $total++;
            }
        }
        return $total;
    }

}