<?php
/* * ********************************************************************
*  ProxmoxVPS Product developed. (27.03.19)
* *
*
*  CREATED BY MODULESGARDEN       ->       http://modulesgarden.com
*  CONTACT                        ->       contact@modulesgarden.com
*
*
* This software is furnished under a license and may be used and copied
* only  in  accordance  with  the  terms  of such  license and with the
* inclusion of the above copyright notice.  This software  or any other
* copies thereof may not be provided or otherwise made available to any
* other person.  No title to and  ownership of the  software is  hereby
* transferred.
*
*
* ******************************************************************** */

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

use MGProvision\Proxmox\v2\Api;
use MGProvision\Proxmox\v2\VmFactory;
use ModulesGarden\ProxmoxAddon\App\Models\IpAddress;
use ModulesGarden\ProxmoxAddon\App\Models\VirtualInterface;
use ModulesGarden\ProxmoxAddon\App\Models\VmIpAddress;
use ModulesGarden\ProxmoxAddon\App\Services\ApiService;
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\Utility;
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\BaseDataProvider;
use Illuminate\Database\Capsule\Manager as DB;
use function ModulesGarden\ProxmoxAddon\Core\Helper\sl;

class IpAddressProvider extends BaseDataProvider implements ClientArea
{
    use ApiService;
    use ProductService;


    private $networkService;
    /**
     * @var IpSetIpFilterService
     */
    private $ipSetIpFilterService;

    /**
     * IpAddressProvider constructor.
     */
    public function __construct()
    {
        parent::__construct();
        $this->networkService       = new NetworkService();
        $this->ipSetIpFilterService = new IpSetIpFilterService();
    }

    public function read()
    {
        if ($this->actionElementId && $this->actionElementId != "diskDataTable")
        {
            $this->data['id'] = $this->actionElementId;
            $this->data['ip'] = VmIpAddress::where("id", $this->actionElementId)->value("ip");
        }
    }

    public function create()
    {
        $ip = new VmIpAddress();
        $ip->fill($this->formData);
        $ip->hosting_id = $this->getWhmcsParamByKey("serviceid");
        $ip->server_id  = $this->getWhmcsParamByKey("serverid");
        $this->networkService->create([$ip]);

        return (new HtmlDataJsonResponse())
            ->setStatusSuccess()
            ->setMessageAndTranslate('The IP Address has been added successfully');
    }

    public function update()
    {
    }

    public function delete()
    {
        try {
            $this->api();
            DB::beginTransaction();
            Api::beginTransaction();
            //delete ip
            /**
             * @var VmIpAddress $ip
             */
            $ip = VmIpAddress::ofHostingId($this->getWhmcsParamByKey('serviceid'))
                ->where("id", $this->formData['id'])
                ->firstOrFail();
            $ip->delete();
            //unlock in proxmox addon
            IpAddress::where('ip', $ip->ip)
                ->where('hosting_id', $ip->hosting_id)
                ->update(["hosting_id" => "0", 'last_check' => Utility::timeStamp()]);
            //delete network device
            if($ip->vm_id && $ip->net){
                $vm = (new VmFactory)->fromVmModel($ip->vmModel);
                sl('Vm')->setVm($vm);
                if($vm->config()[$ip->net]){
                    $vm->deleteConfig($ip->net);
                }
            }
            //delete virtual interface
            VirtualInterface::ofHostingId($ip->hosting_id)
                ->ofIp($ip->ip)
                ->delete();
            //delete in hosting
            $ip->hosting->ipDelete($ip->ip);
            if ($this->configuration()->isIpsetIpFilter() && $vm)
            {
                $this->ipSetIpFilterService->create();
            }
            DB::commit();
            Api::commit();
            return (new HtmlDataJsonResponse())
                ->setStatusSuccess()
                ->setMessageAndTranslate('The IP Address has been deleted successfully');
        }catch (\Exception $ex){
            DB::rollBack();
            Api::commit();
            throw $ex;
        }
    }


}