<?php

// $output = shell_exec("node /var/www/html/FFMPEG-CRON-JOB/ide/temp/unit_36c1b10.js 2>&1");
// $result['status'] = true;
// $result['html'] = $output;
// echo json_encode($result);exit;

$language = strtolower($_POST['language']);

$code = $_POST['code'];
$user_input = $_POST['user_input'];

$random = substr(md5(mt_rand()), 0, 7);

if($language == "php"){
	$code = str_replace("<?php", " ",$_POST['code']);
    
    //create a file for unit test
	$test_random = "test1" . substr(md5(mt_rand()), 0, 7);
    $unitTestfilePath = "/var/www/html/FFMPEG-CRON-JOB/ide/temp/php_test."  . $language;
    $programFile = fopen($unitTestfilePath, "w");
    fwrite($programFile, $code);
    fclose($programFile);
    
    // create a file for output
    $input_code = '<?php 
    $user_input = "' . $user_input . '";';
    $outputfilePath = "/var/www/html/FFMPEG-CRON-JOB/ide/temp/" . $random. "." .$language;
    $programFile = fopen($outputfilePath, "w");
    fwrite($programFile, $input_code . $code);
    fclose($programFile);

} 
else if($language == "node"){    
    //create a file for unit test
    $unitTestfilePath = "/var/www/html/FFMPEG-CRON-JOB/ide/temp/node_test.js";
    $programFile = fopen($unitTestfilePath, "w");
    fwrite($programFile, $code);
    fclose($programFile);
    
    // create a file for output
    $input_code = 'let user_input = "' . $user_input . '";';
    $outputfilePath = "/var/www/html/FFMPEG-CRON-JOB/ide/temp/" . $random. "." .$language;
    $programFile = fopen($outputfilePath, "w");
    fwrite($programFile, $input_code . $code);
    fclose($programFile);

}
else if($language == "python"){    
    //create a file for unit test
    $unitTestfilePath = "/var/www/html/FFMPEG-CRON-JOB/ide/temp/python_test.python";
    $programFile = fopen($unitTestfilePath, "w");
    fwrite($programFile, $code);
    fclose($programFile);
    
    // create a file for output
    $input_code = 'user_input = "' . $user_input . '"; ';
    $outputfilePath = "/var/www/html/FFMPEG-CRON-JOB/ide/temp/" . $random. "." .$language;
    $programFile = fopen($outputfilePath, "w");
    fwrite($programFile, $input_code . $code);
    fclose($programFile);

} 
else if($language == "c"){    
    //create a file for unit test
    $unitTestfilePath = "/var/www/html/FFMPEG-CRON-JOB/ide/temp/c_test." . $language;;
    $programFile = fopen($unitTestfilePath, "w");
    fwrite($programFile, $code);
    fclose($programFile);
    
    // create a file for output
    $input_code = 'char user_input[] = "' . $user_input . '"; 
    ';
    $outputfilePath = "/var/www/html/FFMPEG-CRON-JOB/ide/temp/" . $random. "." . $language;
    $programFile = fopen($outputfilePath, "w");
    fwrite($programFile, $input_code . $code);
    fclose($programFile);

}
else if($language == "cpp"){    
    //create a file for unit test
    $unitTestfilePath = "/var/www/html/FFMPEG-CRON-JOB/ide/temp/cpp_test." . $language;;
    $programFile = fopen($unitTestfilePath, "w");
    fwrite($programFile, $code);
    fclose($programFile);
    
    // create a file for output
    $input_code = 'char* user_input = "' . $user_input . '"; 
    ';
    $outputfilePath = "/var/www/html/FFMPEG-CRON-JOB/ide/temp/" . $random. "." . $language;
    $programFile = fopen($outputfilePath, "w");
    fwrite($programFile, $input_code . $code);
    fclose($programFile);

} else{
    $filePath = "/var/www/html/FFMPEG-CRON-JOB/ide/temp/" . $random. "." .$language;
    $programFile = fopen($filePath, "w");
    fwrite($programFile, $code);
    fclose($programFile);
}


if($language == "php"){
	rename($outputfilePath, $outputfilePath.'.php');
	//start unit test code
	exec("/var/www/html/FFMPEG-CRON-JOB/ide/vendor/bin/phpunit --verbose UnitTestFiles/Test/1/PHPFileTest.php 2>&1",$output,$result_code);
	
	// $result['status'] = true;
	// $result['html'] = $output;
	// echo json_encode($result);exit;
    $original_file_output_cmd = "php $outputfilePath.php 2>&1";
	render_output($output, $original_file_output_cmd);
}

if($language == "python") {
	//start unit test code
	exec("/var/www/html/FFMPEG-CRON-JOB/ide/vendor/bin/phpunit --verbose UnitTestFiles/Test/1/PythonFileTest.php 2>&1",$output,$result_code);
	
    $original_file_output_cmd = "/usr/bin/python3 $outputfilePath 2>&1";
	render_output($output, $original_file_output_cmd);
}
if($language == 'node'){
	
	rename($outputfilePath, $outputfilePath.'.js');
	//start unit test code
	exec("/var/www/html/FFMPEG-CRON-JOB/ide/vendor/bin/phpunit --verbose UnitTestFiles/Test/1/NodeFileTest.php 2>&1",$output,$result_code);
	
	// $result['status'] = true;
	// $result['html'] = $output;
	// echo json_encode($result);exit;
	
    $original_file_output_cmd = "node $outputfilePath.js 2>&1";
	render_output($output, $original_file_output_cmd);

}

if($language == 'c'){
    //start unit test code
	exec("/var/www/html/FFMPEG-CRON-JOB/ide/vendor/bin/phpunit --verbose UnitTestFiles/Test/1/CFileTest.php 2>&1",$output,$result_code);
	
	$outputExe = "/var/www/html/FFMPEG-CRON-JOB/ide/temp/" . $random . ".exe";
    shell_exec("gcc $outputfilePath -o $outputExe");

    $original_file_output_cmd = "$outputExe 2>&1";
	render_output($output, $original_file_output_cmd);
}

if($language == 'cpp'){
    //start unit test code
	exec("/var/www/html/FFMPEG-CRON-JOB/ide/vendor/bin/phpunit --verbose UnitTestFiles/Test/1/CppFileTest.php 2>&1",$output,$result_code);
	
	$outputExe = "/var/www/html/FFMPEG-CRON-JOB/ide/temp/" . $random . ".exe";
    shell_exec("g++ $outputfilePath -o $outputExe");

    $original_file_output_cmd = "$outputExe 2>&1";
	render_output($output, $original_file_output_cmd);
}

$result['status'] = true;
$result['html'] = $output;
echo json_encode($result);exit;


function render_output($output, $original_file_output_cmd)
{
	$testcaseArray = array();
	$time = "";
	$memory = "";
	
    $count = 0;
	foreach($output as $item){
	    
	    if(strpos($item, "Time:") !== false){
	        $memory = get_string_between($item, "Memory:", "");
	        $time = get_string_between($item, "Time:", ", Memory");
	    }
	    
		if(strpos($item, "#") !== false){
		    $val = explode(",", get_string_between($item, "(", ")"));
		    $results = array_map(function($element) {
                    return str_replace("'",'',$element);
                },
                $val
            );
            
            if(!empty($results)) {
    			$testcaseArray[$count]['number'] = ($count + 1);
    			$testcaseArray[$count]['input_output'] = $results;
    			$testcaseArray[$count]['expected'] = "";
    			$testcaseArray[$count]['actual'] = "";
            }
		}
		
		$expected = "";
        $actual = "";
		
    	if(strpos($item, "-'") !== false){
    	    $val = $item;
    	    $val = str_replace('-','',$val);
    	    $val = str_replace("'",'',$val);
    		$testcaseArray[$count]['expected'] = $val;
    	}
    	if(strpos($item, "+'") !== false){
    	    $val = $item;
    	    $val = str_replace('+','',$val);
    	    $val = str_replace("'",'',$val);
    		$testcaseArray[$count]['actual'] = $val;
    		$count++;
    	}
		
	}
	
	if(empty($testcaseArray)) {
	    
	    get_success_html($time,$memory,$original_file_output_cmd, $_POST);
	} else {
	    get_error_html($testcaseArray,$time,$memory);
	}
}


function get_string_between($string, $start, $end){
    $string = ' ' . $string;
    $ini = strpos($string, $start);
    if ($ini == 0) return '';
    $ini += strlen($start);
    if(empty($end)) {
        $len = strlen($string);
    } else {
        $len = strpos($string, $end, $ini) - $ini;
    }
    return substr($string, $ini, $len);
}

function get_error_html($testcaseArray, $time, $memory){
    $html = "";
		
    foreach($testcaseArray as $value) {
        $number = $value['number'];
        $input = $value['input_output'][0];
        $expected = $value['expected'];
        $actual = $value['actual'];
        $html .= '<div class="card">
                <div class="card-header d-flex justify-content-between px-3" id="heading'.$number.'">
                    <div class="d-flex align-items-center"><i
                            class="cursor-pointer fas fa-times-circle fas-style question-error pr-2 collapsed"
                            data-toggle="collapse" data-target="#testcase'.$number.'" aria-expanded="false"
                            aria-controls="testcase'.$number.'"></i>
                        <h6 class="mb-0 d-inline-block font-weight-bold cursor-pointer collapsed" data-toggle="collapse"
                            data-target="#testcase'.$number.'" aria-expanded="false" aria-controls="testcase'.$number.'">Private Testcase #'.$number.'
                        </h6>
                    </div>
                    <div class="d-flex">
                        <div class="accordianIcon accordion-trigger p-0 collapsed" data-toggle="collapse"
                            data-target="#testcase'.$number.'" aria-expanded="false" aria-controls="testcase'.$number.'"></div>
                    </div>
                </div>
                <div id="testcase'.$number.'" class="collapse" aria-labelledby="heading1" data-parent="#accordion" style="">
                    <div class="card-body" >
                        <h5>Testcase Status: </h5>
                        <pre><b>&gt;&gt;&gt; </b>error</pre>
                        <h5>Input: </h5>
                        <pre>'.$input.'</pre>
                        <h5>Expected Output: </h5>
                        <pre>'.$expected.'</pre>
                        <h5>Actual Output: </h5>
                        <pre>'.$actual.'</pre>
                        <h5>Execution Time:</h5>
                        <pre><b>&gt;&gt;&gt; </b>'.$time.'</pre>
                        <h5>Memory Used: </h5>
                        <pre><b>&gt;&gt;&gt; </b>'.$memory.'</pre>
                    </div>
                </div>
            </div>';
    }
    
    $json['status'] = false;
    $json['html'] = $html;
    echo json_encode($json);
    die;
}

function get_success_html($time, $memory, $original_file_output_cmd, $data){
    
    $testcaseArray = [
        ["1 1 1", 3],
        ["15 15", 30],
        ["25 25", 50],
    ];
    $html = "";

	
    $output = shell_exec($original_file_output_cmd);
	
	$output= (int)str_replace("\r\n","",$output);
	$html = '<div class="card">
            <div class="card-header d-flex justify-content-between px-3" id="heading">
                <div class="d-flex align-items-center"><i
                        class="cursor-pointer fas fa-check-circle fas-style question-success pr-2"
                        data-toggle="collapse" data-target="#output" aria-expanded="true"
                        aria-controls="output"></i>
                    <h6 class="mb-0 d-inline-block font-weight-bold cursor-pointer" data-toggle="collapse"
                        data-target="#output" aria-expanded="true" aria-controls="output">Output</h6>
                </div>
                <div class="d-flex">
                    <div class="accordianIcon accordion-trigger p-0" data-toggle="collapse" data-target="#output"
                        aria-expanded="true" aria-controls="output"></div>
                </div>
            </div>
            <div id="output" class="collapse" aria-labelledby="heading" data-parent="#accordion" style="">
                <div class="card-body" >
                        <h5>Input: </h5>
                        <pre>'.$data["user_input"].'</pre>
                        <h5>Output: </h5>
                        <pre>'.$output.'</pre>
                </div>
            </div>
        </div>';
		
    foreach($testcaseArray as $key => $value) {
        $input = $value[0];
        $expected = $actual = $value[1];
        $html .= '<div class="card">
            <div class="card-header d-flex justify-content-between px-3" id="heading1">
                <div class="d-flex align-items-center"><i
                        class="cursor-pointer fas fa-check-circle fas-style question-success pr-2"
                        data-toggle="collapse" data-target="#testcase'.$key.'" aria-expanded="true"
                        aria-controls="testcase'.$key.'"></i>
                    <h6 class="mb-0 d-inline-block font-weight-bold cursor-pointer" data-toggle="collapse"
                        data-target="#testcase'.$key.'" aria-expanded="true" aria-controls="testcase'.$key.'">Private Testcase #'.($key + 1).'</h6>
                </div>
                <div class="d-flex">
                    <div class="accordianIcon accordion-trigger p-0" data-toggle="collapse" data-target="#testcase'.$key.'"
                        aria-expanded="true" aria-controls="testcase'.$key.'"></div>
                </div>
            </div>
            <div id="testcase'.$key.'" class="collapse" aria-labelledby="heading1" data-parent="#accordion" style="">
                <div class="card-body" >
                    <h5>Testcase Status: </h5>
                        <pre><b>&gt;&gt;&gt; </b>success</pre>
                        <h5>Input: </h5>
                        <pre>'.$input.'</pre>
                        <h5>Expected Output: </h5>
                        <pre>'.$expected.'</pre>
                        <h5>Actual Output: </h5>
                        <pre>'.$actual.'</pre>
                        <h5>Execution Time:</h5>
                        <pre><b>&gt;&gt;&gt; </b>'.$time.'</pre>
                        <h5>Memory Used: </h5>
                        <pre><b>&gt;&gt;&gt; </b>'.$memory.'</pre>
                </div>
            </div>
        </div>';
    }
    $json['status'] = true;
    $json['html'] = $html;
    echo json_encode($json);
    die;
} 