<?php

declare(strict_types=1);

namespace App\Http\Livewire\Components\SwitchBox;

use Illuminate\Contracts\View\View;
use Nwidart\Modules\Facades\Module as ModuleFacade;

/**
 * Class ModuleStateSwitch
 *
 * @package App\Http\Livewire\Components\SwitchBox
 */
final class ModuleStateSwitch extends SwitchBox
{
    /**
     * @param string|null $moduleName
     *
     * @return void
     */
    public function mount(?string $moduleName = null): void
    {
        if (is_null($moduleName)) {
            return;
        }

        $this->setProperties($moduleName);
    }

    /**
     * @param string $moduleName
     *
     * @return void
     */
    private function setProperties(string $moduleName): void
    {
        /* @var \Nwidart\Modules\Laravel\Module $module */
        $module = ModuleFacade::findOrFail($moduleName);
        $this->switchId = $module->getLowerName();
        $this->state = $module->isEnabled();
    }

    /**
     * @return \Illuminate\Contracts\View\View
     */
    public function render(): View
    {
        return view('livewire.components.switchbox.switchbox');
    }

    /**
     * @param string|null $moduleName
     *
     * @return void
     */
    public function changeState(?string $moduleName = null): void
    {
        if (is_null($moduleName)) {
            return;
        }

        $module = ModuleFacade::findOrFail($moduleName);
        $module->isEnabled() ? $module->disable() : $module->enable();
    }
}
