<?php
namespace boru\boruai\Cli\Defs;
use boru\cli\params\Option;
use boru\cli\params\Positional;
use boru\output\Output;
use boru\boruai\BoruAI;
use boru\cli\params\Flag;

trait WebUICLI {
    public static function def_webui() {
        return [
            "description"=> "Web UI",
            "params" => [
                Flag::create("i|install|Install the web UI"),
                Flag::create("u|update|Update the web UI"),
                Flag::create("f|force|Force install the web UI"),
                Positional::create("dir|The directory to install the web UI to"),
            ]
        ];
    }

    public function cmd_webui($cmd) {
        $force = $cmd->get("force");
        if($cmd->get("install") || $cmd->get("update")) {
            if($cmd->get("update")) {
                $force = true;
            }
            $dir = $cmd->get("dir");
            if(!$dir) {
                $dir = BoruAI::config("web.dir",false);
            }
            if(!$dir) {
                Output::outLine("No directory specified and no default directory set in config [web.dir].");
                return;
            }
            $this->install($dir,$force);
        } else {
            Output::outLine("No command specified. Use --help for a list of commands.");
        }
    }
    
    private function install($dir,$force=false) {
        if(file_exists($dir) && !$force) {
            Output::outLine("Directory already exists: $dir");
            return;
        }
        if(!is_dir($dir)) {
            mkdir($dir, 0755, true);
        }
        //find the 'web' directory from boruai.. it's either in the root of the project or in the vendor directory
        global $rootDir;
        if(!file_exists($rootDir."/web")) {
            $webDir = $rootDir."/vendor/boru/boruai/web";
        } else {
            $webDir = $rootDir."/web";
        }
        if(!is_dir($webDir)) {
            Output::outLine("Web directory not found: $webDir");
            return;
        }
        //copy the web directory to the specified directory
        $this->copyDir($webDir, $dir);
        //check to see if all the files were copied
        if(!file_exists($dir."/index.php")) {
            Output::outLine("Web directory not found: $dir");
            return;
        }
        Output::outLine("Web UI installed to: $dir");
        Output::outLine("You can now access the ui via the web -- make sure to edit index.php to adjust the path to the init.php file.");
    }

    private function copyDir($src, $dest) {
        $files = scandir($src);
        foreach($files as $file) {
            if($file == "." || $file == "..") {
                continue;
            }
            $srcFile = $src."/".$file;
            $destFile = $dest."/".$file;
            if(is_dir($srcFile)) {
                mkdir($destFile, 0755, true);
                $this->copyDir($srcFile, $destFile);
            } else {
                copy($srcFile, $destFile);
            }
        }
    }
}