<?php
//die();
date_default_timezone_set("Asia/Tehran");
error_reporting(E_ALL);
ini_set('display_errors', '1');
require_once 'functions.php';
$ch = null;
$symbols = [];
$DelistSymbols = [];

$min = date('i');

if ($ch)
    curl_close($ch);

while ($min == date('i')) {
    $tickerPriceUrl = "https://api.binance.com/api/v3/exchangeInfo";
    $tickerPrices = curlb($tickerPriceUrl);
    $DelistSymbols = [];
    if ($tickerPrices) {
        $tickerPrices = json_decode($tickerPrices);
        foreach ($tickerPrices->symbols as $ticker) {
            if (isset($ticker->status) && $ticker->status == 'BREAK' && str_ends_with($ticker->symbol, 'USDT'))
                $DelistSymbols[] = $ticker->symbol;
        }
        if (count($DelistSymbols) > 0) break;
    }
    usleep(500000);
}
if ($ch)
    curl_close($ch);


while ($min == date('i')) {
    $data = sendCurl('https://api.coinex.com/v2/spot/market');
    $data = json_decode($data, true);
    $symbols = [];
    if (isset($data['data'])) {
        foreach ($data['data'] as $v) {
            if ((str_ends_with($v['market'], 'USDT') && $v['is_amm_available'] == false) || $v['market'] == 'CETUSDT')
                $symbols[] = $v['market'];
        }
    } else {
        error_log("no Coinex Market to Create Symbols list");
        sleep(1);
        continue;
    }
    closeCurl();

    $RootDir = '../nobitex/data/binancePrices';
    $files1 = scandir($RootDir);
    $binancePrice = readJson($RootDir . '/' . end($files1));
    if (!$binancePrice) {
        error_log("no binancePrices to Create Symbols list");
        sleep(1);
        continue;
    }
    foreach ($symbols as $key => $symbol)
        if ($symbol!='CETUSDT' && (!property_exists($binancePrice, $symbol) || in_array($symbol, $DelistSymbols)))/* || !property_exists($nobitex, $symbol)*/
            unset($symbols[$key]);


    $symbols = array_values($symbols);
    if (count($symbols) > 80 /*&& count($symbols) < 180*/) break;
    sleep(2);
}
if (count($symbols) > 80 /*&& count($symbols) < 180*/) {
    $filePath = 'data/symbols.json';
    file_put_contents($filePath, json_encode($symbols, JSON_PRETTY_PRINT));
}

function readJson($path)
{
    if (!filesize($path))
        usleep(300000);

    if (!filesize($path))
        return [];

    $file = fopen($path, "r");
    $response = fread($file, filesize($path));
    fclose($file);

    return json_decode($response);
}


function curlb($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);
}