<?php

namespace App\Console\Commands;

use App\Traits\ServiceAppAop;
use Illuminate\Console\Command;
use Illuminate\Support\Str;

class MakeServiceCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'make:service
    {--noProvider : Register in the provider}
    {name : fileName}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Create Service file';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle()
    {
        if (!file_exists(base_path('app\\Services'))){
            mkdir('app\\Services',666,false);
        }
        preg_match('/(.*?)Service/',$this->argument('name'),$resultNames);
        if(count($resultNames)==0) {
            $fileName = $this->argument('name');
            $modelName = $this->argument('name');
        }else{
            $fileName=$resultNames[0];
            $modelName=Str::studly($resultNames[1]);
        }

        if (!file_exists(base_path('app\\Services\\'.$fileName.'.php'))){
            file_put_contents(base_path('app\\Services\\'.$fileName.'.php'),
                '<?php '
                .PHP_EOL
                .PHP_EOL
                .'namespace App\Services;'
                .PHP_EOL
                .PHP_EOL
                .'use App\Traits\ServiceAppAop;'
                .PHP_EOL
                .'use App\\'.$modelName.';'
                .PHP_EOL
                .PHP_EOL
                .'class '.$fileName
                .PHP_EOL
                .'{'
                .PHP_EOL
                .'    use ServiceAppAop;'
                .PHP_EOL
                .'    protected $modelClass='.$modelName.'::class;'
                .PHP_EOL
                .PHP_EOL.
                '}');
        }
        else $this->error("ERROR: file exists;");
        if (!$this->option("noProvider")){
            $path = base_path("app\\Providers\\AppServiceProvider.php");
            $i = 0;
            $fop = fopen($path,"r+");
            $endLine = 0;
            $startLine = 0;
            $sign = 0;
            while (!feof($fop)){
                $i += 1;
                $lineStr = fgets($fop);
                if (strpos($lineStr,"loadingService(){"))$sign = $i;
                if (strpos($lineStr,"app()->singleton"))$endLine = $i;
                if (strpos($lineStr,"App\Services"))$startLine = $i;
            };
            fclose($fop);
            $fop = fopen($path,"r+");
            $i = 0;
            $header = [];
            $content = [];
            $footer = [];
            while (!feof($fop)){
                $i += 1;
                $lineStr = fgets($fop);
                if ($i == $startLine){
                    $lineStr = $lineStr."use App\Services\\$fileName;".PHP_EOL;
                }
                if ($i<=$sign)$header[] = $lineStr;
                if ($i>$sign && $i<= $endLine){
                    $content[] = $lineStr;
                }
                if ($i>$endLine)$footer[] = $lineStr;
            };
            $content[] = "        app()->singleton('{$fileName}',{$fileName}::class);".PHP_EOL;
            array_multisort($content);
            fclose($fop);
            unlink($path);
            foreach (array_merge($header,$content,$footer) as $value){
                file_put_contents($path,$value,FILE_APPEND);
            }
        }
        $this->info("File create success!");
    }

}
