<?php
// +----------------------------------------------------------------------
// | SentCMS [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2025 http://www.tensent.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: molong <molong@tensent.cn> <http://www.tensent.cn>
// +----------------------------------------------------------------------
namespace App\Services\System;

use Nwidart\Modules\Contracts\ActivatorInterface;
use Nwidart\Modules\Module;
use Nwidart\Modules\Facades\Module as ModuleFacade;
use Illuminate\Container\Container;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Artisan;
use App\Models\System\Modules;

class ModulesService implements ActivatorInterface {

    /**
     * 模块管理的模型
     * @var class-string<Model> $modelClass
     */
    private string $modelClass;
    /**
     * Laravel Filesystem instance
     *
     * @var Filesystem
     */
    private $files;

    public function __construct(Container $app) {
        $this->modelClass = $app['config']['modules.activators.database.model'];
		$this->files = $app['files'];
    }

    /**
     * Enables a module
     */
    public function enable(Module $module): void {
        $this->setActiveByName($module->getName(), true);
    }

    /**
     * Disables a module
     */
    public function disable(Module $module): void {
        $this->setActiveByName($module->getName(), false);
    }

    /**
     * Determine whether the given status same with a module status.
     */
    public function hasStatus(Module|string $module, bool $status): bool {
        $name = $module instanceof Module ? $module->getName() : $module;
        $moduleRecord = $this->modelClass::where('name', $name)->first();
        if ($moduleRecord) {
            return boolval($moduleRecord['status']) === $status;
        } else {
            return $status === false;
        }
    }

    /**
     * Set active state for a module.
     */
    public function setActive(Module $module, bool $active): void {
        $this->setActiveByName($module->getName(), $active);
    }

    /**
     * Sets a module status by its name
     */
    public function setActiveByName(string $name, bool $active): void {
		$module = ModuleFacade::getModulePath($name);
		$json = $this->readJson($module . 'module.json');
        $this->modelClass::upsert(['name' => $name, 'status' => $active, 'title' => $json['alias']], ['name'], ['status', 'title']);
    }

    /**
     * Deletes a module activation status
     */
    public function delete(Module $module): void {
        $moduleRecord = $this->modelClass::where('name', $module->getName())->first();
        if ($moduleRecord) {
            $moduleRecord->delete();
        }
    }

    /**
     * Deletes any module activation statuses created by this class.
     */
    public function reset(): void {
        $this->modelClass::truncate();
    }


	public function getDataList($request){
		$map = [];

		if($request->filled('title')){
			$map[] = ['title', 'like', '%' . $request->input('title') . '%'];
		}

		$query = Modules::where($map)->orderBy('id', 'asc');

		if($request->filled('page')){
			$data = [
				'total' => $query->count(),
				'page' => $request->input('page', 1),
				'data' => $query->offset($request->input('offset', 0))->limit($request->input('limit', 10))->get(),
			];
		}else{
			$data = $query->get();
		}
		return $data;
	}

	public function update($request){
		if($request->filled('name')){
			$name = $request->input('name');
			$module = ModuleFacade::getModulePath($name);
			$json = $this->readJson($module . 'module.json');

			$module = Modules::where('name', $name)->first();

			$module->title = $json['alias'];

			$module->save();
			return $module;
		}
	}

	/**
     * Reads the json file that contains the activation statuses.
     *
     * @throws FileNotFoundException
     */
    private function readJson($file): array {
        if (! $this->files->exists($file)) {
            return [];
        }

        return $this->files->json($file);
    }
}
