<?php
namespace UnitTestFiles\Test;
use PHPUnit\Framework\TestCase;

class NodeFileTest extends TestCase
{
    /**
     * @dataProvider additionProvider
     */
    public function testAdd($val, $expected)
    {
        $random = substr(md5(mt_rand()), 0, 7);
        $input_code = 'let user_input = "' . $val . '";';
        
        $filePath = "/var/www/html/FFMPEG-CRON-JOB/ide/temp/unit_" . $random. ".js";
        $unitTestfilePath = "/var/www/html/FFMPEG-CRON-JOB/ide/temp/node_test.js";
        $code = file_get_contents($unitTestfilePath);
        $programFile = fopen($filePath, "w");
        fwrite($programFile, $input_code . $code);
        fclose($programFile);

        $output = shell_exec("node $filePath 2>&1");
        $output= str_replace("\n","",$output);
        $expected= str_replace("\n","",$expected);
        
        $this->expectOutputString($expected);
        unlink($filePath);
        print $output;
    }

    

    public function additionProvider()
    {
        $id = file_get_contents("/var/www/html/FFMPEG-CRON-JOB/ide/temp/record_id.php");
        $url = "https://reviewnprep.com/get-ide-test-cases/" . $id;
        $response = $this->callApi($url,[]);
        if ($response->status == true) {
            $result = (array)json_decode($response->data);
            return (array)$result;
        } else {
            return [];
        }
    }

    public function callApi($url, $data, $isReturnJson = 1)
    {
        $this->error_logger("URL - " . $url);
        try {
            $postvars = '';
            foreach ($data as $key => $value) {
                $postvars .= $key . "=" . $value . "&";
            }

            $ch = curl_init();

            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            $server_output = curl_exec($ch);
            // print_r($server_output);exit;
            curl_close($ch);
            $result = json_decode($server_output);
            if ($isReturnJson == 1) {
                return $result;
            } else {
                return $server_output;
            }
        } catch (\Exception $e) {
            $this->error_logger("Message - " . $e->getMessage());
            exit;
            return false;
        }
    } 

    public function error_logger($message, $logFile = "error_unit_test.txt"){
        $filePath = "/var/www/html/FFMPEG-CRON-JOB/ide/temp/" . $logFile;
        $file = fopen($filePath, "a");
        fwrite($file, $message . "\n");
        fclose($file);
        return true;
    }

}

?>