<?php
//die();
date_default_timezone_set("Asia/Tehran");
error_reporting(E_ALL);
ini_set('display_errors', '1');
//set_time_limit(59);
$ch = null;

//====================================================================== start main
$min = date('i');
do {
    $CoinexOrderBooks = [];

    $CoinexOrderBooks = curl('http://www.samisun.ir/api/data?type=orderbooks&symbol=' . (time()-1));
    if ($CoinexOrderBooks) {
        $CoinexOrderBooks = json_decode($CoinexOrderBooks);
        if (isset($CoinexOrderBooks->BTCUSDT)) {
            $myfile1 = fopen('data/CoinexOrderBook/'.time().'.json', "w") or die("Unable to open file!");
            if (flock($myfile1, LOCK_EX)) {
                fwrite($myfile1, json_encode($CoinexOrderBooks));
                flock($myfile1, LOCK_UN);
            }
            fclose($myfile1);
        }
    }
    usleep(400000);

} while ($min == date('i'));

if ($ch)
    curl_close($ch);

//removeOldFiles();




function curl($url)
{
    global $ch;
    if (!$ch) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Connection: keep-alive'
        ]);
        curl_setopt($ch, CURLOPT_TIMEOUT, 2);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

    }

    curl_setopt($ch, CURLOPT_URL, $url);
    return curl_exec($ch);
}


//function removeOldFiles()
//{
//    $files = scandir('binancePrices');
//    foreach ($files as $file) {
//        if ($file == '.' || $file == '..')
//            continue;
//        $file = str_replace('.json', '', $file);
//        if ($file < time() - 85)
//        {
//            $path = "binancePrices/$file.json";
//            if (file_exists($path))
//                unlink($path);
//        }
//    }
//}