<?php 
namespace Sargilla\Canvas\Console;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;
use Illuminate\Filesystem\Filesystem;

/**
 * Class Publish FlatLab.
 */
class InstallCanvas extends Command
{

    protected $files;

    /**
     * The name and signature of the console command.
     */
    protected $signature = 'canvas:install {--f|force : Force overwrite of files}';    

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Instalación de Componente Páginas';

    /**
     * Force overwrite of files.
     *
     * @var bool
     */
    protected $force = false;

    /**
     * Create a new command instance.
     *
     * @param \Illuminate\Filesystem\Filesystem $files
     *
     */
    public function __construct( FileSystem $files)
    {
        parent::__construct();
        $this->files = $files;
    }

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $this->processOptions();
        $this->presetCanvas();
        $this->publishAssets();
        $this->modificarEnvPlantilla();
        $this->compilar();
    }

    private function publishAssets()
    {
        $this->comment('Publicando Assets');
        $this->call('vendor:publish',['--tag'=>'canvas']);
        File::copyDirectory(CANVAS_PATH . '/resources/views/', resource_path('/views/layout/canvas/'));
        $path = base_path('/webpack.mix.js');
        $webpack = File::get($path);
        $mix = "\r\nmix.js('resources/canvas/app.js', 'canvas/all.js')\r\n.sass('resources/canvas/app.scss', 'canvas/all.css');\r\n";
        if (!str_contains($webpack, $mix)) {
            File::append($path, $mix);
        }
    }
    private function presetCanvas()
    {
        $this->comment('Realizando preset Canvas');
        $this->call('preset', ['type' => 'canvas']);
    }
    private function modificarEnvPlantilla()
    {
        $path = app()->environmentFilePath();
        $key="PLANTILLA";
        $escaped = preg_quote('='.env($key), '/');

        File::put($path,preg_replace(
            "/^{$key}{$escaped}/m",
            "{$key}=canvas",
            file_get_contents($path)
        ));
    }
    private function compilar() {
        $this->comment('Compilando Assets');
        passthru('yarn run dev');
    }

    private function processOptions()
    {
        $this->force = $this->option('force');
    }
}
