<?php
namespace jaguarjack\think\module\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;

class DiscoverModuleServiceCommand extends Command
{
    protected function configure()
    {
        $this->setName('module:service')
            ->setDescription('discover module service');
    }

    protected function execute(Input $input, Output $output)
    {
        $this->getModuleServices();

        $output->writeln('module service generator succeed!');
    }

    /**
     * 获取模块
     *
     * @time 2019年11月27日
     * @return bool
     * @throws \ReflectionException
     */
    protected function getModuleServices(): bool
    {
        $modules = glob(root_path('module') .'*');
        $moduleServices = [];

        foreach ($modules as $module) {
            if (file_exists($module . DIRECTORY_SEPARATOR . 'module.json')) {
                $moduleJson = file_get_contents($module . DIRECTORY_SEPARATOR . 'module.json');
                $moduleServices = array_merge($moduleServices, \json_decode($moduleJson, true)['services']);
            }
        }

        $moduleServices = $this->checkModuleService($moduleServices);

        $header = '// This file is automatically generated at:' . date('Y-m-d H:i:s') . PHP_EOL . 'declare (strict_types = 1);' . PHP_EOL;

        $content =
            '<?php ' . PHP_EOL . $header . 'return ' .

            var_export($moduleServices, true) . ';';

        file_put_contents($this->app->getRootPath() . 'module/services.php', $content);

        return true;
    }

    /**
     *
     * @time 2019年11月29日
     * @param $moduleServices
     * @throws \ReflectionException
     * @return mixed
     */
    protected function checkModuleService($moduleServices)
    {
        $new = [];

        foreach ($moduleServices as $key => $service) {
            $selfReflection = new \ReflectionClass($service);
            // if service set property 'cache' && set cache => false
            // the service will not be cached
            // finally  will boot it
            if ($selfReflection->hasProperty('cache') && !$selfReflection->getProperty('cache')) {
                $new[$service] = true;
            } else {
                $new[$service] = false;
            }
        }

        return $new;
    }
}
