<?php

/* 
 *
 *
 *
 */
require_once 'asyncRequst.php';

class OSWindows {

    function __construct() {
        
    }

    public static function getCmdForStatisticReq($username) {
        global $CURRENT_SOURCE_FOLDER, $PHP_FOLDER;
        $v2 = $_REQUEST['v2'] ?? null;
        
        $cmd = "start /B " . "$CURRENT_SOURCE_FOLDER\\run_graph.bat \"$PHP_FOLDER\" parseUtils.php \"r\" \"getStatistic\" \"$username\"  \"$v2\" > NUL ";
        return $cmd;
    }

    public static function getCmdForGetPieReq($username, $pieName, $isAdmin) {
        global $CURRENT_SOURCE_FOLDER, $PHP_FOLDER;
        $v2 = $_REQUEST['v2'] ?? null;
        $cmd = "start /B " . "$CURRENT_SOURCE_FOLDER\\run_graph.bat \"$PHP_FOLDER\" StatisticPageEng.php \"r\" \"$username\" \"$pieName\" \"$isAdmin\" \"$v2\" > NUL ";
        return $cmd;
    }

    public static function getCmdForTrendReq($username, $trendName, $isAdmin) {
        global $CURRENT_SOURCE_FOLDER, $PHP_FOLDER;
        $v2 = $_REQUEST['v2'] ?? null;
        $cmd = "start /B " . "$CURRENT_SOURCE_FOLDER\\run_graph.bat \"$PHP_FOLDER\" proSentPageEng.php \"r\" \"$username\" \"$trendName\" \"$isAdmin\" \"$v2\" > NUL";
        return $cmd;
    }

    public static function getCmdForSendDocReq($i, $user, $serverIP, $port, $file_id, $isEmail) {
        global $CURRENT_SOURCE_FOLDER, $PHP_FOLDER;
        $cmd = "start /B " . "$CURRENT_SOURCE_FOLDER\\sendDoc_batch.bat \"$PHP_FOLDER\" \"$i\" \"$user\" \"$serverIP\" \"$port\" \"$file_id\" \"0\" \"$isEmail\" > NUL ";
        return $cmd;
    }

    public static function getCmdForBackgroundReq($arr, $getmetadata) {
        global $CURRENT_SOURCE_FOLDER, $PHP_FOLDER;
        $cmd = "$CURRENT_SOURCE_FOLDER/cnm_batch.bat \"$PHP_FOLDER\" $arr[docId] \"$getmetadata\" > NUL";
        return $cmd;
    }

    public static function getCmdForPhpPage($isBackground, $pageName, $args) {
        global $CURRENT_SOURCE_FOLDER;
        global $PHP_FOLDER;
        $cmd = "$CURRENT_SOURCE_FOLDER\\run_graph.bat \"$PHP_FOLDER\" $pageName \"" . join("\" \"", $args) . "\" > NUL";
        if ($isBackground) {
            $cmd = "start /B " . $cmd;
        }
        return $cmd;
    }
    
    public static function getCmdForCrawler($twitterBK){
        global $CURRENT_SOURCE_FOLDER;
        global $PHP_FOLDER;        
        $cmd = $PHP_FOLDER. DIRECTORY_SEPARATOR ."php.exe ". $CURRENT_SOURCE_FOLDER.DIRECTORY_SEPARATOR."tools".DIRECTORY_SEPARATOR."cowitter".DIRECTORY_SEPARATOR."cli_runner.php filter_stream_db_twitter $twitterBK";        
        $cmd = "start /B " . $cmd;
        return $cmd;    
    }
    
    public static function getCmdForFilter(){
        global $CURRENT_SOURCE_FOLDER;
        global $PHP_FOLDER;
        $cmd = $PHP_FOLDER. DIRECTORY_SEPARATOR ."php.exe ". $CURRENT_SOURCE_FOLDER.DIRECTORY_SEPARATOR."tools".DIRECTORY_SEPARATOR."cowitter".DIRECTORY_SEPARATOR."cli_runner.php filter_and_parse_db_ui";
        $cmd = "start /B " . $cmd;
        return $cmd;   
    }
    
    public static function getSolrCoreCommand($SOLR_COLLECTION) {
        return "solr create -c $SOLR_COLLECTION";
    }
    
	public static function wrapCmd($cmd, $add_null = null) {
	    $null_pointer = ($add_null) ? " > NUL" : "";
        return "start /B $cmd $null_pointer";
    
    }
    
    public static function getDirectoryIterator($folder) {
        return new IVDirectoryIterator($folder);
    }
    
    public static function getOfficePath(){
        global $sofficePath;
        $ret_path = "";
        if(is_dir($sofficePath['win_86'])){
            $ret_path = $sofficePath['win_86'];
        }
        elseif(is_dir($sofficePath['win'])){
            $ret_path = $sofficePath['win'];
        }
        else{
            write_to_log("ERROR", "LibreOffice isn't installed on your windows machine");
            return null;
        }
        return $ret_path."/soffice.exe";
    }
    
    public function exec_run($CURRENT_SOURCE_FOLDER, $cmd, $letter = null){
        executeCommand($CURRENT_SOURCE_FOLDER, $cmd, $letter);        
    }
    
    public function getCMDPdfConvert(){
        $cmd = "gswin64 -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dNOPAUSE -dQUIET -dBATCH -sOutputFile=".$outputPath."_new ".$path." 2>&1";
        return $cmd;
    }
    
    
    public function copyFolder($origDir, $destDir){
        system("robocopy \"$origDir\" \"$destDir\" /E /NFL /NDL /NJH /NJS");
    }
    
    public function rmDir($dir){
        executeCommand(NULL, "rmdir /s /q \"$dir\"");
    }
}

class IVDirectoryIterator implements Iterator
{
    var $dirLines;
    var $dirIndex = 24;
    var $lineIndex;
    var $fileName;
    var $shortFileName;
    var $folderPath;
    var $inEmail;
    var $stat;
    
    function __construct ($folderPath)
    {
        $this->dirLines = array();
        $returnVal;
        global $TEMP_FOLDER;
        global $user;
        system("cmd.exe /U /c dir /x /s \"" . $folderPath . "\" > $TEMP_FOLDER/dirFiles_$user.txt", $returnVal);
        //  system("bash -c  ls /x * \"" . $folderPath . "\" > $TEMP_FOLDER/dirFiles_$user.txt", $returnVal);
        $lines = iconv("UTF-16LE", "UTF-8", file_get_contents("$TEMP_FOLDER/dirFiles_$user.txt"));
        $this->dirLines = explode("\r\n", $lines);
        $this->lineIndex = -1;
        $this->next();
    }
    function getFilename() {return $this->fileName;}
    function getShortFilename() {return $this->shortFileName;}
    function getPath() { return $this->folderPath;}
    function isInEmail() {return $this->inEmail;}
    function getStat() {return $this->stat;}
    function current() : mixed
    {
        return $this;
    }
    function next() : void
    {
        for ($this->lineIndex++; $this->valid(); $this->lineIndex++)
        {
            $dirLine = $this->dirLines[$this->lineIndex];
            $dirIndex = strpos($dirLine, "<DIR>");
            if ($dirIndex)
            {
                $this->dirIndex = $dirIndex;
                continue;
            }
            
            if (strpos($dirLine, " Directory of ") === 0)
            {
                $this->folderPath = substr($dirLine, strlen(" Directory of "));
                //use relative path if applicable
                global $CURRENT_SOURCE_FOLDER;
                if (stripos($this->folderPath, $CURRENT_SOURCE_FOLDER) === 0)
                {
                    $this->folderPath = trim(substr($this->folderPath, strlen($CURRENT_SOURCE_FOLDER)), DIRECTORY_SEPARATOR);
                }
                //special treatment for IV email folders
                $lastFolder = basename($this->folderPath);
                $this->inEmail = isEmailfolder($lastFolder);
                continue;
            }
            //skip general info lines
            if (strpos($dirLine, " ") === 0)
                continue;
                
                $this->fileName = substr($dirLine, $this->dirIndex + 28);
                if (!$this->fileName) continue;
                
                //for filenames with unicode characters - use old DOS format
                $this->shortFileName = trim(substr($dirLine, $this->dirIndex + 15, 12));
                
                $fullFileName = $this->getPath() . DIRECTORY_SEPARATOR . $this->fileName;
                $this->stat = stat($fullFileName);
                if (empty($this->stat))
                {
                    try {
                        $mtime = new DateTime(substr($dirLine, 0, 20));
                    }
                    catch (Exception $e)
                    {
                        write_to_log("ERROR", "Failed to parse modified time from: $dirLine");
                        $mtime = null;
                    }
                    if ($mtime)
                    {
                        $this->stat = array("mtime" => $mtime->getTimestamp());
                    }
                    else write_to_log("ERROR", "Failed to get modified time of: $fullFileName");
                }
                //found a valid file name
                break;
        }
    }
    
    function valid() : bool
    {
        return $this->lineIndex < count($this->dirLines);
    }
    function key() : mixed{ }
    function rewind() : void{ }
     
}
