<?php
$KoolControlsFolder = "../KoolPHPSuite/KoolControls";
require $KoolControlsFolder . "/KoolAjax/koolajax.php";
require "../DM/http-request/HttpRequest.php";

$koolajax->scriptFolder = $KoolControlsFolder."/KoolAjax";

$services = [
    ["name" => "geo", "url" => "http://saas-searchproxy-maps-prestable.yandex.net:17000/?service=geosuggest&", "checked" => true],
    ["name" => "geo backend", "url" => "http://imgs28-032.search.yandex.net:7316/?service=geosuggest&normal_kv_report=yes&noqtree=yes&gta=_UrlOnly", "checked" => false],
    ["name" => "geo debug", "url" => "http://arachnid10.haze.yandex.net:8505/?service=geosuggest&normal_kv_report=yes&noqtree=yes&gta=_UrlOnly", "checked" => false]
];

$flags = [
    [
        "caption" => "dict", "type" => "radio", "group" => "dict", "flags" => [
            ["name" => "orgs", "cgi" => "&relev=dict=suggest", "caption" => "orgs", "checked" => true],
            ["name" => "tops", "cgi" => "&relev=dict=toponym_suggest;title_prop=fullpath", "caption" => "tops"],
            ["name" => "tops_parent", "cgi" => "&relev=dict=toponym_parent;title_prop=fullpath", "caption" => "tops parent"],
            ["name" => "tops_street", "cgi" => "&relev=dict=toponym_street;title_prop=fullpath", "caption" => "street"],
            ["name" => "tops_locality", "cgi" => "&relev=dict=toponym_locality;title_prop=fullpath", "caption" => "locality"],
            ["name" => "tops_province", "cgi" => "&relev=dict=toponym_province;title_prop=fullpath", "caption" => "province"],
            ["name" => "tops_country", "cgi" => "&relev=dict=toponym_country;title_prop=fullpath", "caption" => "country"]
        ]
    ], [
        "caption" => "Text", "type" => "checkbox", "flags" => [
            ["name" => "no_twin", "cgi" => "&pron=notwin", "caption" => "no twin"],
            ["name" => "no_reorder", "cgi" => "&pron=noreorder", "caption" => "no reorder"],
            ["name" => "no_msp_hypothesis", "cgi" => "&pron=nomsphypothesis", "caption" => "no msp hypothesis"],
            ["name" => "no_fetch", "cgi" => "&haha=da", "caption" => "no fetch"],
            ["name" => "uniq_docids", "cgi" => "&pron=uniqdocids", "caption" => "uniq docids"]
        ]
    ], [
        "caption" => "Erratum misspels", "type" => "radio", "group" => "msp", "flags" => [
            ["name" => "msp_no", "cgi" => "&msp=no", "caption" => "no", "checked" => true],
            ["name" => "msp_force", "cgi" => "&msp=force", "caption" => "force"],
            ["name" => "msp_taf", "cgi" => "&msp=try_at_first", "caption" => "try at first"]
        ]
    ], [
        "caption" => "Sort by", "type" => "radio", "group" => "sort_by", "flags" => [
            ["name" => "sort_by_global__weight", "caption" => "global rating", "cgi" => "&relev=formula=pruning_rank", "checked" => true],
            ["name" => "sort_by_regional_weight", "caption" => "regional rating", "cgi" => "&relev=calc=weight:if(%23region_weight,%23region_weight,%23global_weight)", "checked" => false],
            ["name" => "sort_by_proximity", "caption" => "proximity", "cgi" => "&relev=formula=3001000GM46M4;calc=weight:proximity(%23longitude,%23latitude,37.588124177997365,55.73386850415982)", "checked" => false]
        ]
    ], [
        "caption" => "Language:", "type" => "radio", "group" => "language", "flags" => [
            ["name" => "lang_rus", "caption" => "rus", "cgi" => "&relev=language=rus", "checked" => true],
            ["name" => "lang_en", "caption" => "en", "cgi" => "&relev=language=en", "checked" => false],
            ["name" => "lang_ukr", "caption" => "ukr", "cgi" => "&relev=language=ukr", "checked" => false]
        ]
    ], [
        "caption" => "Sort houses by:", "type" => "radio", "group" => "housesort", "flags" => [
            ["name" => "weight", "caption" => "weight", "cgi" => "&relev=house_sort=weight", "checked" => true],
            ["name" => "number", "caption" => "number", "cgi" => "&relev=house_sort=number", "checked" => false]
        ]
    ], [
        "caption" => "house report:", "type" => "radio", "group" => "housereport", "flags" => [
            ["name" => "hr", "caption" => "hr", "cgi" => "&relev=house_report=hr", "checked" => false],
            ["name" => "indexes", "caption" => "indexes", "cgi" => "&relev=house_report=indexes", "checked" => true]
        ]
    ], [
        "caption" => "Options:", "type" => "checkbox", "group" => "options", "flags" => [
            ["name" => "factors", "caption" => "factors", "cgi" => "&fsgta=_JsonFactors", "checked" => false]
        ]
    ], [
        "caption" => "Grouping:", "type" => "checkbox", "group" => "groupings", "flags" => [
            ["name" => "use_grouping", "caption" => "group", "cgi" => "", "checked" => false],
            ["name" => "custom", "caption" => "custom", "cgi" => "&relev=search_type=custom", "checked" => false],
            ["name" => "organizations", "caption" => "orgs", "cgi" => "&relev=search_type=organizations", "checked" => true],
            ["name" => "toponyms", "caption" => "toponyms", "cgi" => "&relev=search_type=toponyms", "checked" => true],
        ]
    ]
];
function get_suggest($request) {
    try {
        $http = HttpRequest::get($request);
        $response = $http->body();
        return ["code" => $http->code(), "response" => $http->body()];
    } catch (HttpRequestException $e) {
        return ["500" => $http->code(), "response" => $e->getMessage()];
    }
} 
$koolajax->enableFunction("get_suggest");
echo $koolajax->Render();
?>

<script type="text/javascript">
var services = JSON.parse('<?php echo json_encode($services);?>');
var flags = JSON.parse('<?php echo json_encode($flags);?>');

function onSuggestDone(response) {
    if (response.code == 200) {
        var responseObj = JSON.parse(decodeURIComponent(response.response));
        var html = "<table><tr>";
        var sugg = Object();
        if ("Grouping" in responseObj && responseObj.Grouping.length > 0) {
            var groups = responseObj.Grouping[0].Group;
            for (i = 0; i < groups.length; ++i) {
                for (d = 0; d < groups[i].Document.length; ++d) {
                    var doc = groups[i].Document[d];
                    var sugText = doc.Relevance + "\t" + doc.DocId;
                    if ("ArchiveInfo" in doc) {
                        sugText += "\t";
                        if ("Url" in doc.ArchiveInfo)
                            sugText += doc.ArchiveInfo.Url;
                        sugText += "\t";
                        if ("Title" in doc.ArchiveInfo)
                            sugText += doc.ArchiveInfo.Title;
                        if ("GtaRelatedAttribute" in doc.ArchiveInfo) {
                            var houses = [];
                            for (a = 0; a < doc.ArchiveInfo.GtaRelatedAttribute.length; ++a) {
                                if (doc.ArchiveInfo.GtaRelatedAttribute[a].Key == 'matched_house') {
                                    value = doc.ArchiveInfo.GtaRelatedAttribute[a].Value.replace(/\\/gi, '');
                                    h = JSON.parse(value);
                                    houses.push(h.number + "(" + h.match +")");
                                }
                            }
                            if (houses.length > 0)
                                sugText += "[" + houses.join() + "]";
                        }
                    }
                    if ("FirstStageAttribute" in doc) {
                        for (fsgta = 0; fsgta < doc.FirstStageAttribute.length; ++fsgta) {
                            if (doc.FirstStageAttribute[fsgta].Key == "_JsonFactors") {
                                sugText += "\t" + doc.FirstStageAttribute[fsgta].Value;
                            }
                        }
                    }
                    if (!(groups[i].CategoryName in sugg))
                        sugg[groups[i].CategoryName] = "";
                    sugg[groups[i].CategoryName] += sugText +  "\n";
                }
            }
            for (var s in sugg) {
                html += "<td align='center'><h2>" + s + "</h2><br>";
                html += '<textarea rows="40" cols="102" readonly="1" wrap="off" id="text_area_' + s + '"></textarea></td>';
            }
        } else {
                html += '<td><br><textarea rows="40" cols="102" readonly="1" wrap="off"></textarea></td>';
        }
        html += "</tr></table>";
        document.getElementById("text_elapsed").value = responseObj.BalancingInfo.Elapsed;
        document.getElementById("text_output").innerHTML = html;
        for (var s in sugg) {
            document.getElementById('text_area_' + s).value = sugg[s];
        }
    } else {
        document.getElementById("text_status").value = response.code + " " + response.response;
        document.getElementById("text_output").innerHTML = '<br><textarea rows="40" cols="102" readonly="1" wrap="off"></textarea>';
        document.getElementById("text_elapsed").value = "";
    }
}

function processSuggest() {
    var input = document.getElementById("text_input");
    var text = encodeURIComponent(input.value);
    for (i = 0; i < flags.length; ++i)
        for (j = 0; j < flags[i].flags.length; ++j)
            if (document.getElementById("cb_" + flags[i].flags[j].name).checked)
                text += flags[i].flags[j].cgi;
    url = document.getElementById("form_service").elements["url"].value;
    var grMode = document.getElementById("cb_use_grouping").checked ? 1 : 0;
    url += "&g=" + grMode + ".search_type.5." + document.getElementById("numdoc").value;
    url += "&qs_req=" + document.getElementById("region").value;
    url += "&ms=proto&hr=json&text=" + text;
    document.getElementById("text_status").value = url;
    koolajax.callback(get_suggest(url), onSuggestDone);
}

</script>
<html>
    <head>
        <meta charset="UTF-8">
        <link rel="shortcut icon" href="icon.bmp" type="image/bmp">
        <title>SAAS suggest</title>
    </head>
    <body>
        <table>
        <tr><td>
        <form id="form_service">
        Service
        <?php
        foreach($services as $service) {
            echo "<input onchange='processSuggest()' type='radio' name='url' value='" . $service["url"] . "'" . ($service["checked"] ? " checked='1'" : "") . ">" . $service["name"] . "</input>";
        }
        ?>
        </form>
        </td></tr>
        <tr><td><input id="text_input" type="list" placeholder="Введите текст" onkeyup="processSuggest()" autofocus="1" size="100"/></td></tr>
        <tr><td><table>
        <tr>
            <td>Docs count <input id="numdoc" onchange="processSuggest()" type="number" value="10" step="10"/></td>
            <td>Region <input id="region" onchange="processSuggest()" type="number" value="213" step="1"/></td>
        </tr>
        <?php
        foreach($flags as $flags_line) {
            echo "<tr><td>" . $flags_line["caption"] . "</td><td>";
            foreach($flags_line["flags"] as $flag) {
                echo "<input onchange='processSuggest()' type='". $flags_line["type"] . "' id='cb_" . $flag["name"] . "' name='" . $flags_line["group"] . "'" . ($flag["checked"] ? " checked='1'" : "") . ">" . $flag["caption"] . "</input>";
            }
            echo "</td></tr>";
        }
        ?>
        </table></td></tr>
        <tr><td>Time elapsed: <input id="text_elapsed" type="text" size="6" readonly="1"/> us</td></tr>
        <tr><td><div id="text_output"><br><textarea rows="40" cols="102" readonly="1" wrap="off"></textarea></div></td></tr>
        <tr><td><textarea id="text_status" rows="11" cols="102" readonly="1"></textarea></td></tr>
        </table>
    </body>
</html>

