<?php
namespace ModulesGarden\ProxmoxAddon\App\UI\CloudInitScriptCreate\Providers;

use ModulesGarden\ProxmoxAddon\App\Models\CloudInitScript;
use ModulesGarden\ProxmoxAddon\Core\UI\ResponseTemplates\HtmlDataJsonResponse;
use ModulesGarden\ProxmoxAddon\Core\UI\Widget\Forms\DataProviders\BaseModelDataProvider;
use function ModulesGarden\ProxmoxAddon\Core\Helper\sl;

class CloudInitScriptProvider extends BaseModelDataProvider
{


    /**
     * CloudInitScriptProvider constructor.
     * @param string $model
     */
    public function __construct()
    {
        parent::__construct(CloudInitScript::class);
    }

    public function read()
    {
        $this->actionElementId = $this->getRequestValue('id');
        return parent::read(); // TODO: Change the autogenerated stub
    }

    public function create()
    {
        $this->formData['meta'] = trim($this->formData['meta']);
        $this->formData['script'] = trim($this->formData['script']);
        $this->formData['network'] = trim($this->formData['network']);
        parent::create();
        sl('lang')->addReplacementConstant('name', $this->formData['name']);
        return (new HtmlDataJsonResponse(['id' => $this->model->id]))
            ->setMessageAndTranslate('Cloud-Init Script :name: has been added successfully')
            ->setCallBackFunction('pkOnCloudInitScriptCreatedAjaxDone');
    }

    public function update()
    {
        $this->formData['meta'] = trim($this->formData['meta']);
        $this->formData['script'] = trim($this->formData['script']);
        $this->formData['network'] = trim($this->formData['network']);
        if (!$this->formData['id'])
        {
            return $this->create();
        }
        parent::update();
        sl('lang')->addReplacementConstant('name', $this->formData['name']);
        return (new HtmlDataJsonResponse(['id' => $this->model->id]))->setMessageAndTranslate('Cloud-Init Script :name: has been updated successfully');
    }
}