<?php
$addable_service_types = ["rtyserver", "metaservice"];
$editable_service = in_array($service_type_cgi, $addable_service_types);
?>
<script type="text/javascript">
    var binary_file = "";

    var fields = {
        enums: {
            "Shard by": {"json_key": "shard_by", "values": ["keyprefix", "url_hash", "time", "external", "geo", "geo_restrict", "url_hash_erasure", "querysearch"]},
            "Shards count": {"json_key": "shards", "values": ["legacy", "ui32"]},
            "Indexing target": {"json_key": "dispatch_target", "values": ["backends", "distributor"]}
        },
        strings: {
            "Distributors": {"json_key": "distributors"},
            "Stream": {"json_key": "stream"}
        }
    };

    var boolFields = {
        "Require authorisation": {"json_key": "require_auth", "value": false},
        "Per DC search": {"json_key": "per_dc_search", "value": false}
    };

    var locations = ["SAS", "MAN", "VLA"];

    var addableServiceTypes = JSON.parse('<?php echo json_encode($addable_service_types) ?>');
    var service_cgi = "<?php echo $service_cgi ?>";
    var service_type_cgi = "<?php echo $service_type_cgi ?>";
    var ctype_cgi = "<?php echo $ctype_cgi; ?>";
    var metaservice = service_type_cgi == "metaservice";

    function bin2hex(s) {
        var i, f = s.length, a = [];
        for (i = 0; i < f; i++) {
            var c = s.charCodeAt(i).toString(16);
            a[i] = c.length < 2 ? '0' + c : c;
        }
        return a.join('');
    }

    function hex2bin(hex) {
        var result = "";
        var bytes = [];
        for (var i = 0; i < hex.length - 1; i += 2) {
            if (bytes.length === 1024) {
                result += String.fromCharCode.apply(String, bytes);
                bytes = [];
            }
            bytes.push(parseInt(hex.substr(i, 2), 16));
        }
        if (bytes.length > 0) {
            result += String.fromCharCode.apply(String, bytes);
        }
        return result;
    }

    function saveData(url, data, callback) {
        koolajax.callback(post_request_to_dm("set_conf?hex=yes&service=&root=/&filename=" + url, bin2hex(data)),
                function(s) {
                    callback("<table><tr><td>" + url + "</td><td>" + s.reply + "</td></tr></table>", url, s.success);
                }
        );
    }

    function btn_add_OnClick() {
        var btn = document.getElementById("btn_add");
        btn.disabled = true;
        var element = document.getElementById("path_add");
        if (element.value !== "") {
            saveData(btn.getAttribute("url") + "/" + element.value, "new_file", onAddDone);
        }
    }

    function btn_submit_OnClick() {
        document.getElementById("btn_submit").disabled = true;
        var element = document.getElementById("text_edit");
        saveData(element.getAttribute("url"), element.value, onSubmitDone);
    }

    function btn_encode_polynom_OnClick(service) {
        document.getElementById("btn_encode_polynom").disabled = true;
        document.getElementById("btn_decode_polynom").disabled = true;
        koolajax.callback(post_request_to_dm("fml_ops?action=encode&service=" + service, document.getElementById("te_polinom_hr").value), onPolynomEncoded);
    }

    function btn_decode_polynom_OnClick(service) {
        document.getElementById("btn_encode_polynom").disabled = true;
        document.getElementById("btn_decode_polynom").disabled = true;
        koolajax.callback(post_request_to_dm("fml_ops?action=decode&service=" + service, document.getElementById("te_polinom_coded").value), onPolynomDecoded);
    }

    function onPolynomEncoded(s) {
        document.getElementById("btn_encode_polynom").disabled = false;
        document.getElementById("btn_decode_polynom").disabled = false;
        document.getElementById("te_polinom_coded").value=s.reply;
    }

    function onPolynomDecoded(s) {
        document.getElementById("btn_encode_polynom").disabled = false;
        document.getElementById("btn_decode_polynom").disabled = false;
        document.getElementById("te_polinom_hr").value=s.reply;
    }

    function onAddDone(s, p, success) {
        if (success) {
            redirect({"file_path": p, "path": document.getElementById("btn_add").getAttribute("url")}, [], "path_text");
            return;
        }
        document.getElementById("btn_add").disabled = false;
        document.getElementById("info").innerHTML = s;
    }

    function onSubmitDone(s, p, success) {
        document.getElementById("btn_submit").disabled = false;
        document.getElementById("info").innerHTML = s;
        rebuildVersions(p, -1);
    }

    function btn_upload_OnClick() {
        document.getElementById("btn_upload").disabled = true;
        document.getElementById("upload_file_path").click();
    }

    function uploadFiles(files) {
        for (var i = 0, f; f = files[i]; i++) {

            var reader = new FileReader();

            // Closure to capture the file information.
            reader.onload = (function(theFile) {
                return function(e) {
                    var element = document.getElementById("text_edit");
                    element.value = e.target.result;
                    saveData(element.getAttribute("url"), e.target.result, onUploadDone);
                };
            })(f);

            reader.readAsBinaryString(f);
        }
    }

    function onFileSelect() {
        var files = document.getElementById("upload_file_path").files;
        uploadFiles(files);
    }

    function handleFileSelect(evt) {
        evt.stopPropagation();
        evt.preventDefault();

        var files = evt.dataTransfer.files; // FileList object.
        uploadFiles(files);
    }

    function handleDragOver(evt) {
        evt.stopPropagation();
        evt.preventDefault();
        evt.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy.
    }

    function onUploadDone(s, p, success) {
        document.getElementById("btn_upload").disabled = false;
    }

    function btn_remove_OnClick() {
        if (window.confirm('Вы уверены?') === true) {
            var element = document.getElementById("btn_remove");
            element.disabled = true;
            if (element.hasAttribute("url")) {
                koolajax.callback(get_request_from_dm("process_storage?action=rm&path=" + element.getAttribute("url")), onDoneRemove);
            }
        }
    }

    function onDoneRemove(s) {
        if (s.success) {
            redirect({"path": document.getElementById("btn_add").getAttribute("url")}, ["file_path"], "path_text");
            return;
        }
        document.getElementById("text_edit").value = "";
        document.getElementById("btn_submit").disabled = true;
    }

    function btn_fml_upload_OnClick() {
        document.getElementById("btn_upload_from_fml").disabled = true;
        var formulaName = document.getElementById("fml_formula_name").value + ".info-" + service_cgi;
        var fmlId = document.getElementById("fml_task_id").value;
        var path = document.getElementById("btn_add").getAttribute("url");
        koolajax.callback(get_request_from_dm("fetch_fml_formula?&fml_id=" + fmlId + "&target_name=" + formulaName + "&path=" + path), btn_fml_upload_OnDone);
    }

    function btn_fml_upload_OnDone(s) {
        document.getElementById("btn_upload_from_fml").disabled = false;
        if (s.success) {
            document.getElementById("fml_task_id").value = "";
            document.getElementById("fml_formula_name").value = "";
            var path = document.getElementById("btn_add").getAttribute("url");
            buildFileList(path, "");
        } else {
            document.getElementById('info').innerText = s.reply;
        }
    }

    function rebuildVersions(path, currentVersion) {
        document.getElementById("version_buttons").innerHTML = "Get versions...";
        var dirPath = path.split('/');
        var filename = dirPath.pop();
        var dirPathStr = dirPath.join('/');
        koolajax.callback(get_request_from_dm("process_storage?action=get&hex=yes&path=/history/" + dirPathStr), function(data) {onVersionsGet(data, path, currentVersion);});
    }

    function fillText(s, version, rebuildVersion=true) {
        var textEdit = document.getElementById("text_edit");
        document.getElementById("file_name").innerHTML = s;
        textEdit.setAttribute("url", s);
        textEdit.value = "Loading...";
        document.getElementById("btn_remove").setAttribute("url", s);
        koolajax.callback(get_request_from_dm("process_storage?action=get&hex=yes&path=" + s + "&version=" + version), onFillText);
        if (rebuildVersion) {
            rebuildVersions(s, version);
        }
    }

    function onClickVersion(path, newVersion) {
        fillText(path, newVersion, false);
    }

    function onVersionsGet(s, path, currentVersion) {
        if (!s.success)
            return;
        var data = JSON.parse(s.reply);
        var filename = path.split('/').pop();
        var html = "";
        if ('files' in data) {
            var elemCount = 0;
            html += "<table><tr>";
            for (var i = data.files.length-1; i >= 0 && elemCount < 10; --i) {
                var f = data.files[i];
                if (f.length > 10 && f.substr(0, f.length - 10) == filename) {
                    var version = parseInt(f.substr(filename.length));
                    var current = "";
                    if (version == currentVersion || (currentVersion == -1 && elemCount == 0)) {
                        current = " checked"
                    }
                    elemCount++;
                    html += "<td><table><tr><td align='center'>"
                    html += "<input type='radio' name='version' value='" + version + "' id='btn_version_" + version +"' onclick='onClickVersion(\"" + path + "\"," + version +")'" + current + ">";
                    html += "</td></tr><tr><td align='center'>";
                    html += "<label for='btn_version_" + version + "'>" + version +"</label>";
                    html += "</td></tr></table></td>";
                }
            }
            html += "</tr></table>";
        }
        document.getElementById("version_buttons").innerHTML = html;
    }

    function onFillText(s) {
        var dropZone = document.getElementById("text_edit");
        dropZone.addEventListener('dragover', handleDragOver, false);
        dropZone.addEventListener('drop', handleFileSelect, false);

        if (s.success)
            dropZone.value = hex2bin(JSON.parse(s.reply).data);
        else
            dropZone.value = s.reply;
        dropZone.disabled = false;
        document.getElementById("btn_upload").disabled = false;
        document.getElementById("btn_submit").disabled = false;
        document.getElementById("btn_remove").disabled = false;
    }

    function buildPathText(path) {
        var dirs = path.split(/\/|\\/);
        var result = "<a style='color:brown;text-decoration:underline;cursor: pointer' onclick='directoryClick(\"/\")'>root</a>";
        var url = "";
        for (var i = 0; i < dirs.length; ++i) {
            if (dirs[i] == "")
                continue;
            url += "/" + dirs[i];
            result += "/<a style='color:brown;text-decoration:underline;cursor: pointer' onclick='directoryClick(\"" + url + "\")'>" + dirs[i] + "</a>";
        }
        return result;
    }

    function buildFileList(path, file_path) {
        document.getElementById("path_text").innerHTML = buildPathText(path);
        koolajax.callback(get_request_from_dm("process_storage?action=get&path=" + path), function(s) {
            onDirClick(path, s);
        });
        if (file_path != "") {
            fillText(file_path, -1);
        }
    }

    function directoryClick(path) {
        document.getElementById("dir_list").innerHTML = "Loading...";
        buildFileList(path, "");
    }

    function getClusterMap() {
<?php
if ($editable_service && $service_cgi != "") {
    echo "koolajax.callback(get_request_from_dm(\"get_cluster_map?ctype=$ctype_cgi&service=$service_cgi&service_type=$service_type_cgi\"), onClusterMapLoaded);\n";
};
?>
    }

    function onDirClick(path, s) {
        document.getElementById("dir_list").innerHTML = "Parsing...";
        var files_info = {};
        if (s.success)
            files_info = JSON.parse(s.reply);
        var dirs_list = "";
        if (path != "/") {
            var dir = path.substr(0, path.lastIndexOf("/"));
            dirs_list += "<a style='color:brown;text-decoration:underline;cursor: pointer' onclick='directoryClick(\"" + dir + "\")'>..</a><br/>";
        }
        if ("dirs" in files_info)
            for (i = 0; i < files_info.dirs.length; ++i) {
                var dir = files_info.dirs[i];
                dirs_list += "<a style='color:brown;text-decoration:underline;cursor: pointer' onclick='directoryClick(\"" + path + "/" + dir + "\")'>" + dir + "</a><br/>";
            }
        if ("files" in files_info)
            for (i = 0; i < files_info.files.length; ++i) {
                var file = files_info.files[i];
                dirs_list += "<a style='color:green;text-decoration:underline;cursor: pointer' onclick='fillText(\"" + path + "/" + file + "\",-1)'>" + file + "</a>"
                        + " <a style='color:green' href='<?php echo get_dm_url()?>process_storage?action=get&download=yes&path=" + path + "/" + file + "' download='download.file'>D</a>"
                        + "<br/>";
            }
        document.getElementById("dir_list").innerHTML = dirs_list;
        document.getElementById("btn_add").setAttribute("url", path);
    }

    function removeEmptyMetaServiceComponents() {
        var table = document.getElementById("meta_service_components");
        var lastIndex = table.rows.length - 2;
        for (; lastIndex > 0; --lastIndex)
            if (table.rows[lastIndex].cells[0].firstChild.value == "")
                table.deleteRow(lastIndex);
    }

    function addMetaServiceComponent(component) {
        var table = document.getElementById("meta_service_components");
        var row = table.insertRow(-1);
        row.align = "center";
        row.insertCell(-1).innerHTML = "<input list='services_list' placeholder='service name' oninput='onChangeServiceName()' value='" + component.ServiceName + "'/>";
        row.insertCell(-1).innerHTML = "<input type='checkbox'" + (component.SearchDisabled ? " checked='1'" : "") + "/>";
        row.insertCell(-1).innerHTML = "<input type='checkbox'" + (component.IndexDisabled ? " checked='1'" : "") + "/>";
        row.insertCell(-1).innerHTML = "<input type='number' min='0' max='1000' value='" + component.SearchPriority + "'/>";
    }
    function addMetaServiceComponentIfNeed() {
        var table = document.getElementById("meta_service_components");
        var index = table.rows.length - 1;
        if (index <= 0 || table.rows[index].cells[0].firstChild.value != "")
            addMetaServiceComponent({ServiceName: "", IndexDisabled: false, SearchDisabled: false, SearchPriority: 0});
    }

    function onChangeServiceName() {
        removeEmptyMetaServiceComponents();
        addMetaServiceComponentIfNeed();
    }

    function onClickEditServiceSubmit() {
        var form = document.getElementById("service_properties");
        var service = {};

        for (var type in fields) {
            for (var caption in fields[type]) {
                var name = fields[type][caption].json_key
                service[name] = form.elements[name].value;
            }
        }
        for (var caption in boolFields) {
            var name = boolFields[caption].json_key
            service[name] = form.elements[name].checked;
        }
        if (form.elements.dc_matrix_enabled.checked) {
            service["locations_weights"] = {};
            for (var l in locations) {
                service["locations_weights"][locations[l]] = {};
                for (var k in locations) {
                    service["locations_weights"][locations[l]][locations[k]] = parseInt(form.elements["weight_" + locations[l] + "_" + locations[k]].value, 10);
                }
            }
        }
        if (metaservice) {
            service.Name = service_cgi;
            service.Components = [];
            var table = document.getElementById("meta_service_components");
            for (var i = 1; i < table.rows.length - 1; ++i) {
                service.Components[i - 1] = {"ServiceName": table.rows[i].cells[0].firstChild.value,
                    "SearchDisabled": table.rows[i].cells[1].firstChild.checked,
                    "IndexDisabled": table.rows[i].cells[2].firstChild.checked,
                    "SearchPriority": table.rows[i].cells[3].firstChild.value
                };
            }
        }
        var serviceInfo = encodeURIComponent(JSON.stringify(service));
        var btn = document.getElementById("btn_edit_service_submit");
        btn.disabled = true;
        btn.value = "In progress...";
        document.getElementById("btn_service_remove").disabled = true;
        koolajax.callback(get_request_from_dm("modify_searchmap?action=edit_service&service=" + service_cgi + "&ctype="
                + ctype_cgi + "&service_type=" + service_type_cgi + "&service_info=" + serviceInfo), onDoneEditService);
    }

    function onDoneEditService(s) {
        var btn = document.getElementById("btn_edit_service_submit");
        btn.disabled = false;
        btn.value = "Submit";
        document.getElementById("btn_service_remove").disabled = false;
        if (s.success) {
            document.getElementById("edit_service_info").innerHTML = "OK";
        } else {
            document.getElementById("edit_service_info").innerHTML = s.reply;
        }
    }

    function onDcWeightChanged() {
        document.getElementById("dc_matrix_enabled").checked = true;
    }

    function onClusterMapLoaded(result) {
        if (!result.success) {
            getClusterMap();
            return;
        }
        var service = JSON.parse(result.reply).cluster[service_cgi];
        var html = "<form id='service_properties'><table><tr><td style=\"vertical-align:top;\"><h4>Service parameters</h4><table>";
        for (var caption in fields.enums) {
            var field = fields.enums[caption];
            var value = field.values[0];
            if (field.json_key in service && service[field.json_key] != "") {
                var v = service[field.json_key];
                if (field.json_key == "shard_by")
                    v = v.split('-')[0];
                value = v;
            }
            html += "<tr><td>" + caption + ":</td><td>";
            for (var i = 0; i < field.values.length; ++i)
                html += "<label style=\"white-space:nowrap;\"><input name=" + field.json_key + " type='radio' value='" + field.values[i] + "'" + (value == field.values[i] ? " checked='1'" : "") + "/>" + field.values[i] + "</label> ";
            html += "</td></tr>";
        }
        for (var caption in fields.strings) {
            var field = fields.strings[caption];
            html += "<tr><td>" + caption + ":</td><td><input name=" + field.json_key + " type='text' size='40' value='" + (field.json_key in service ? service[field.json_key] : "") + "'/></td></tr>";
        }
        for (var caption in boolFields) {
            var field = boolFields[caption];
            html += "<tr><td>" + caption + ":</td><td><input name=" + field.json_key + " type='checkbox'" + (field.json_key in service && service[field.json_key] ? " checked='1'" : "") + "/>";
        }

        var enabled = "locations_weights" in service ? "checked" : "";
        html += "</table></td><td style=\"vertical-align:top;\"><h4 style='display:inline-block;' >Datacenter weights: </h4><input type='checkbox' name='dc_matrix_enabled' id='dc_matrix_enabled' " + enabled + ">Enabled</input><table border='1'><tr><td>From\\To</td>";
            for (var l in locations) {
                html += "<td>" + locations[l] + "</td>";
            }
            html += "</tr>";
            for (var l in locations) {
                html += "<tr><td>" + locations[l] + "</td>";
                for (var k in locations) {
                    var value = 0;
                    if ("locations_weights" in service && locations[l] in service.locations_weights && locations[k] in service.locations_weights[locations[l]]) {
                        value = service.locations_weights[locations[l]][locations[k]];
                    }
                    var input_name = "weight_" + locations[l] + "_" + locations[k];
                    html += "<td>" + "<input value='" + value + "' name='" + input_name + "' type='number' style='width: 50px;' onchange='onDcWeightChanged()'></input>" + "</td>";
                }
                html += "</tr>";
            }
        html += "</table></td></tr></table></form>"
        if (metaservice) {
            html += "<h4>Metaservice components</h4>";
            html += "<table id='meta_service_components' border='1' cellpandding='3' cellspacing='0'><tr align='center'>";
            html += "<td>service name</td>";
            html += "<td>no search</td>";
            html += "<td>no indexing</td>";
            html += "<td>search priority</td>";
            html += "</tr></table>";
        }
        html += "<input id='btn_edit_service_submit' type='button' onclick='onClickEditServiceSubmit()' value='Submit'/>";
        html += "<input id='btn_service_remove' type='button' onclick='onClickServiceRemove()' value='Remove service'/>";
        document.getElementById("edit_service").innerHTML = html;
        if (metaservice) {
            if ("Components" in service)
                for (var i = 0; i < service.Components.length; ++i)
                    addMetaServiceComponent(service.Components[i]);
            removeEmptyMetaServiceComponents();
            addMetaServiceComponentIfNeed();
        }
    }

    function onClickServiceRemove() {
        if (window.confirm('Are you sure to delete service ' + service_cgi + '?') !== true)
            return;
        var btn = document.getElementById("btn_service_remove");
        btn.disabled = true;
        btn.value = "In progress...";
        document.getElementById("btn_edit_service_submit").disabled = true;
        koolajax.callback(get_request_from_dm("modify_searchmap?action=remove_service&service=" + service_cgi + "&ctype="
                + ctype_cgi + "&service_type=" + service_type_cgi), onDoneRemoveService);
    }

    function disabledAddBtns(disabled) {
        for (var i in addableServiceTypes) {
            document.getElementById("btn_add_" + addableServiceTypes[i] + "_service").disabled = disabled;
            document.getElementById("btn_copy_" + addableServiceTypes[i] + "_service").disabled = disabled;
        }
    }
    function onClickAddSerivce(serviceType) {
        if (!validateServiceCreation(true)) {
            return false;
        }

        document.getElementById("btn_add_" + serviceType + "_service").value = "in progress...";
        disabledAddBtns(true);
        var service_name = document.getElementById("service_name").value;
        koolajax.callback(get_request_from_dm("modify_searchmap?action=add_service&service=" + service_name + "&ctype=" + ctype_cgi + "&service_type=" + serviceType),
                function(s) {
                    if (s.success) {
                        submitOwnersInfo(service_name, ctype_cgi, true, function(s) {
                            onDoneAddService(serviceType, service_name, s);
                        });
                    } else {
                        onDoneAddService(serviceType, service_name, s);
                    }
                });
    }

    function onClickCopyService(serviceType) {
        if (!validateServiceCreation(true)) {
            return false;
        }
        document.getElementById("btn_copy_" + serviceType + "_service").value = "in progress...";
        var service_name = document.getElementById("service_name").value;
        koolajax.callback(get_request_from_dm("copy_service?from=" + service_cgi + "&to=" + service_name + "&ctype=" + ctype_cgi + "&service_type=" + serviceType),
                function(s) {
                    if (s.success) {
                        koolajax.callback(get_request_from_dm("modify_searchmap?action=add_service&service=" + service_name + "&ctype=" + ctype_cgi + "&service_type=" + serviceType),
                            function(s) {
                                if (s.success) {
                                    submitOwnersInfo(service_name, ctype_cgi, function(s) {
                                        onDoneAddService(serviceType, service_name, s)
                                    });
                                } else {
                                    onDoneAddService(serviceType, service_name, s);
                                }
                            }
                        );
                    } else {
                        onDoneAddService(serviceType, service_name, s);
                    }
                });
    }

    function redirect(replaceParams, deleteParams, scrollTo) {
        var queryString = {};
        var query = window.location.search.substring(1);
        var vars = query.split("&");
        for (var i = 0; i < vars.length; i++) {
            var pair = vars[i].split("=");
            if (typeof queryString[pair[0]] === "undefined") {
                queryString[pair[0]] = pair[1];
            } else if (typeof queryString[pair[0]] === "string") {
                var arr = [queryString[pair[0]], pair[1]];
                queryString[pair[0]] = arr;
            } else {
                queryString[pair[0]].push(pair[1]);
            }
        }
        for (var param in deleteParams)
            delete queryString[deleteParams[param]];
        for (var param in replaceParams)
            queryString[param] = replaceParams[param];
        var newUrl = window.location.protocol + "//" + window.location.host + window.location.pathname + "?";
        for (var param in queryString)
            if (typeof queryString[param] === "string")
                newUrl += "&" + param + "=" + queryString[param];
            else
                for (var i in queryString[param])
                    newUrl += "&" + param + "=" + queryString[param][i];
        if (typeof scrollTo === "string") {
            newUrl += "#" + scrollTo;
        }
        else {
            newUrl += window.location.hash;
        }
        window.location.href = newUrl;
    }

    function validateServiceCreation(checkServiceName) {
        var inputs = document.getElementById('add_service_panel').getElementsByTagName('INPUT');
        var allRight = true;

        var checkElement = function(inputElement) {
            if (inputElement.value.trim().length == 0) {
                inputElement.style.borderColor = 'red';
                return false;
            } else if (inputElement.style.borderColor == 'red') {
                inputElement.style.borderColor = '';
            }
            return true;
        };

        for (var i = 0, len = inputs.length; i < len; i++) {
            var inputElement = inputs[i];
            if (inputElement.type != 'text') {
                continue;
            }
            if (inputElement.hasAttribute('required') && !checkElement(inputElement)) {
                allRight = false;
            }
        }
        if (checkServiceName) {
            if (!checkElement(document.getElementById('service_name'))) {
                allRight = false;
            }
        }
        if (!allRight) {
            document.getElementById("add_service_info").innerHTML = "Required fields are empty";
        } else {
            document.getElementById("add_service_info").innerHTML = "";
        }
        return allRight;
    }

    function updateTicketLink(ticketValue) {
        if (ticketValue.length > 0) {
            var ticketUrl = ticketValue;
            if (ticketValue.indexOf('https://') != 0) {
                ticketUrl = 'https://st.yandex-team.ru/' + ticketValue;
            }
            var linkElement = document.getElementById('service_ticket_link');
            linkElement.href = ticketUrl;
            linkElement.style.display = "";
        } else {
            var linkElement = document.getElementById('service_ticket_link');
            linkElement.href = "";
            linkElement.style.display = "none";
        }

    }

    function updateABCLink(abcValue, fieldType) {
        if (fieldType == 'user_service') {
            var abcLinkType = 'service_abc_user_link'
        } else if (fieldType == 'quota_service') {
            var abcLinkType = 'service_abc_quota_link'
        }
        if (abcValue) {
            var abcUrl = 'https://abc.yandex-team.ru/services/' + abcValue;
            var linkElement = document.getElementById(abcLinkType);
            linkElement.href = abcUrl;
            linkElement.style.display = "";
        } else {
            var linkElement = document.getElementById(abcLinkType);
            linkElement.href = "";
            linkElement.style.display = "none";
        }

    }

    function onClickSubmitOwnersInfo() {
        if (!validateServiceCreation(false)) {
            return false;
        }
        var submitButton = document.getElementById("btn_submit_owners_info");
        submitButton.setAttribute('data-old-name', submitButton.value);
        submitButton.value = "in progress...";
        submitButton.disabled = true;
        submitOwnersInfo(service_cgi, ctype_cgi, false,  onDoneSubmitOwnersInfo);
        return false;
    }

    function submitOwnersInfoItem(json, key, elementId) {
        var value = document.getElementById(elementId).value.trim();
        if (value.length > 0) {
            json[key] = value;
        }
        return value;
    }

    function submitOwnersInfo(serviceName, ctype, onCreate, callback) {
        var convertValue = function(elementId) {
            var valueStr = document.getElementById(elementId).value;
            var res = [];
            var valueSplit = valueStr.split(",");
            for (var i = 0, l = valueSplit.length; i < l; i++) {
                var sValue = valueSplit[i].trim();
                if(sValue.length > 0) {
                    res.push(sValue);
                }
            }
            return res;
        };
        var value = {};
        value["owners"] = convertValue("service_owners");
        value["responsibles"] = convertValue("service_responsibles");
        value["ferrymans"] = convertValue("service_ferrymans");

        updateTicketLink(submitOwnersInfoItem(value, "ticket", "service_ticket"));
        updateABCLink(submitOwnersInfoItem(value, "abc_user_service", "abc_user_service"), "user_service");
        updateABCLink(submitOwnersInfoItem(value, "abc_quota_service", "abc_quota_service"), "quota_service");

        submitOwnersInfoItem(value, "maxdocs", "service_soft_maxdocs");
        submitOwnersInfoItem(value, "search_rps", "search_rps");
        submitOwnersInfoItem(value, "search_rps_planned", "search_rps_planned");
        submitOwnersInfoItem(value, "index_rps", "index_rps");
        submitOwnersInfoItem(value, "total_index_size_bytes", "total_index_size_bytes");
        submitOwnersInfoItem(value, "search_q_99_ms", "search_q_99_ms");
        submitOwnersInfoItem(value, "search_q_999_ms", "search_q_999_ms");
        submitOwnersInfoItem(value, "unanswers_5min_perc_warn", "unanswers_5min_perc_warn");
        submitOwnersInfoItem(value, "unanswers_5min_perc_crit", "unanswers_5min_perc_crit");
        submitOwnersInfoItem(value, "service_weight", "service_weight");
        submitOwnersInfoItem(value, "service_weight", "disaster_alerts");

        var postData = JSON.stringify(value);
        var useDefaultParam = onCreate ? "&use_default=true" : "";
        koolajax.callback(post_request_to_dm("process_sla_description?action=set&service=" + serviceName + "&ctype=" + ctype + useDefaultParam, postData, 0),
            function(s) {
                if (callback) {
                    callback(s);
                }
            }
        );
    }

    function onDoneSubmitOwnersInfo(s) {
        if (s.success) {
            var submitButton = document.getElementById("btn_submit_owners_info");
            submitButton.value = submitButton.getAttribute('data-old-name');;
            submitButton.disabled = false;
        } else {
            document.getElementById("add_service_info").innerHTML = s.reply;
        }
    }

    function fillOwnersInfoItem(data, propertyName, elementId) {
        if (typeof elementId == "undefined") {
            elementId = propertyName;
        }
        if (data.hasOwnProperty(propertyName)) {
            document.getElementById(elementId).value = data[propertyName];
        }
    }

    function fillOwnersInfo(serviceName, ctype) {
        koolajax.callback(get_request_from_dm("process_sla_description?action=get&service=" + serviceName + "&ctype=" + ctype),
            function(s) {
                if (s.success) {
                    var data = JSON.parse(s.reply);
                    var convertValue = function(elementId, key) {
                        document.getElementById(elementId).value = data[key] ? data[key].join(", ") : "";
                    };
                    convertValue("service_owners", "owners");
                    convertValue("service_responsibles", "responsibles");
                    convertValue("service_ferrymans", "ferrymans");

                    var ticketStr = "";
                    var abcUserServiceId = "";
                    var abcQuotaServiceId = "";
                    if (data["ticket"]) {
                        ticketStr = data["ticket"];
                        document.getElementById("service_ticket").value = ticketStr;
                    }
                    if (data["abc_user_service"]) {
                        abcUserServiceId = data["abc_user_service"];
                        document.getElementById("abc_user_service").value = abcUserServiceId;
                    }
                    if (data["abc_quota_service"]) {
                        abcQuotaServiceId = data["abc_quota_service"];
                        document.getElementById("abc_quota_service").value = abcQuotaServiceId;
                    }

                    updateTicketLink(ticketStr);
                    updateABCLink(abcUserServiceId, "user_service");
                    updateABCLink(abcQuotaServiceId, "quota_service");

                    fillOwnersInfoItem(data, "maxdocs", "service_soft_maxdocs");
                    fillOwnersInfoItem(data, "search_rps");
                    fillOwnersInfoItem(data, "search_rps_planned");
                    fillOwnersInfoItem(data, "index_rps");
                    fillOwnersInfoItem(data, "total_index_size_bytes");
                    fillOwnersInfoItem(data, "search_q_99_ms");
                    fillOwnersInfoItem(data, "search_q_999_ms");
                    fillOwnersInfoItem(data, "unanswers_5min_perc_warn");
                    fillOwnersInfoItem(data, "unanswers_5min_perc_warn");
                    fillOwnersInfoItem(data, "unanswers_5min_perc_crit");
                    fillOwnersInfoItem(data, "service_weight");
                    fillOwnersInfoItem(data, "disaster_alerts");
                }
                onDoneSubmitOwnersInfo(s);
        });
    }

    function getAlertsInfo(serviceName, ctype) {
        koolajax.callback(read_reply_from_mon('alert_check?service=' + serviceName + '&ctype=' + ctype),
        function(s){
            if ( !ctype.startsWith("stable") ) { return; }
            var el = document.getElementById('alerts_status');
            if (! s.success) {
                console.log('cannot get alerts actuality : ' + s.reply);
                return;
            }
            console.log(s.reply);
            reply_js = JSON.parse(s.reply);
            var is_act = reply_js.is_actual;
            if (is_act) {
                el.innerText = 'Edit';
                el.style.color = 'green';
            } else{
                el.innerText = 'Outdated alerts';
                el.style.color = 'red';
            }
        });
    }

    function onDoneAddService(serviceType, service_name, s) {
        if (s.success) {
            redirect({"service_type": serviceType, "service": service_name, "path": (metaservice ? "common" : ("configs/" + service_name))}, []);
        } else {
            disabledAddBtns(false);
            document.getElementById("btn_add_" + serviceType + "_service").value = "Add " + serviceType;
            document.getElementById("btn_copy_" + serviceType + "_service").value = "Add " + serviceType;
            document.getElementById("add_service_info").innerHTML = s.reply;
        }
    }

    function onDoneRemoveService(s) {
        if (s.success) {
            redirect({"path": "common"}, ["service_type", "service"]);
        } else {
            var btn = document.getElementById("btn_service_remove");
            btn.disabled = false;
            btn.value = "Remove service";
            document.getElementById("btn_edit_service_submit").disabled = false;
            document.getElementById("edit_service_info").innerHTML = s.reply;
        }
    }

    window.onload = function() {
        var path = "<?php echo $path_cgi ?>";
        var file_path = "<?php echo $file_path_cgi ?>";
        buildFileList(path, file_path);
        getClusterMap();
        getAlertsInfo(service_cgi, ctype_cgi);
        fillOwnersInfo(service_cgi, ctype_cgi);
    }
</script>

<?php
function getEditor() {
    global $path_cgi;
    global $service_cgi;
    global $services;
    global $full_interface;
    global $addable_service_types;
    global $editable_service;

    $editor = "<a id='file_name' value=''/>filename</a>"
            . "<div id='version_buttons'></div>"
            . "<textarea name='text_edit_file' "
            . "id='text_edit' url='test' style='width:100%;height:500px;' dm_url='". get_dm_url() . "set_conf?service=&root=/&filename='>"
            . "</textarea>"
            . "<span>"
            . "<input id='btn_submit' disabled='true' type='button' value='Submit' onclick='btn_submit_OnClick()' />"
            . "<input id='btn_remove' disabled='true' type='button' value='Remove' onclick='btn_remove_OnClick()' />"
            . "<input id='btn_add' type='button' url='$path_cgi' value='Add' onclick='btn_add_OnClick()' />"
            . "<input id='path_add' type='text' value=''/>"
            . "<input id='btn_upload' disabled='true' type='button' url='$path_cgi' value='Upload' onclick='btn_upload_OnClick()' />"
            . "</span>"
            . "<span>"
            . "<input type='file' id='upload_file_path' style='display:none' onchange='onFileSelect()'> "
            . "<input type='number' value='' id='fml_task_id' style='width:75px' placeholder='FML id'/> "
            . "<span><input type='text' value='' id='fml_formula_name' style='width:75px' placeholder='File name'/>.info-$service_cgi</span> "
            . "<input id='btn_upload_from_fml' type='button' value='FML Copy' onclick='btn_fml_upload_OnClick()' />"
            . "</span>"
            . "<br/>"
            . "<span id='info'>Info</span>"
;

    if (read_reply_from_dm("secret_key?service=$service_cgi", $json_info_sk)) {
        $keys_info = json_decode($json_info_sk, true);
    } else {
        $keys_info = array();
    }
    $report_keys = "<h3>Secret keys</h3><table width='100%' border='2' frame='void'>";
    foreach ($keys_info as $ctype_name => $ctype_info) {
        if (array_key_exists($service_cgi, $ctype_info)) {
            $report_keys .= "<tr><td colspan='2' align='center'><b>$ctype_name</b></td></tr>";
            foreach ($ctype_info[$service_cgi] as $key => $value) {
                $report_keys .= "<tr><td>$key</td><td>$value</td></tr>";
            }
            $report_keys .= "</tr>";
        }
    }
    $report_keys .= "</table>";


    $report_poly = "<h3>Polynom conversion</h3><table width='100%' border='0' frame='void'>";
    $report_poly .= "<tr align='center'><td><h4>Human readable</h4></td><td/><td><h4>Encoded</h4></td></tr>";
    $report_poly .= "<tr>"
                .     "<td><textarea name='text_polinom_hr' id='te_polinom_hr' url='test' style='width:100%;height:100px;'></textarea></td>"
                . "<td align='center'>"
                . "<input id='btn_encode_polynom' type='button' value='->' onclick='btn_encode_polynom_OnClick(\"$service_cgi\")'/><br>"
                . "<input id='btn_decode_polynom' type='button' value='<-' onclick='btn_decode_polynom_OnClick(\"$service_cgi\")'/>"
                . "</td>"
                . "<td><textarea name='text_polinom_coded' id='te_polinom_coded' url='test' style='width:100%;height:100px;'></textarea></td>"
                . "</tr></table>";
    $report_file_manager = "<table width='100%' border='2'>";

    // Add service
    if ($full_interface) {
        $req_mark = "<font color='red' style='font-size:small'>*</font>";
        $report_file_manager .= "<tr><td><table id='add_service_panel'><tr><td><h3>Add service</h3>";
        $report_file_manager .= "<input id='service_name' type='text' value='' />$req_mark";
        $report_file_manager .= "</td>";
        $report_file_manager .= "<td><table>";
        $report_file_manager .= "<tr>";
        $report_file_manager .= "<td align='right'>Owners:</td><td><input id='service_owners' type='text' value='' required />$req_mark</td>";
        $report_file_manager .= "<td align='right'>Search RPS:</td><td><input id='search_rps' type='number' value='' /></td>";
        $report_file_manager .= "<td align='right'>Search Q99 ms:</td><td><input id='search_q_99_ms' type='number' value='' /></td>";
        $report_file_manager .= "</tr>";
        $report_file_manager .= "<tr>";
        $report_file_manager .= "<td align='right'>Responsibles:</td><td><input id='service_responsibles' type='text' value='' required />$req_mark</td>";
        $report_file_manager .= "<td align='right'>Search RPS Planned:</td><td><input id='search_rps_planned' type='number' value='' /></td>";
        $report_file_manager .= "<td align='right'>Search Q999 ms:</td><td><input id='search_q_999_ms' type='number' value='' /></td>";
        $report_file_manager .= "</tr>";
        $report_file_manager .= "<tr>";
        $report_file_manager .= "<td align='right'>Ticket:</td><td><input id='service_ticket' type='text' value='' /> <a id='service_ticket_link' href='#' target='blank' style='display:none;font-size:small;'>Link</a></td>";
        $report_file_manager .= "<td align='right'>Index RPS:</td><td><input id='index_rps' type='number' value='' /></td>";
        $report_file_manager .= "<td align='right'>Unanswers precent warn (5min):</td><td><input id='unanswers_5min_perc_warn' type='text' value='' /></td>";
        $report_file_manager .= "</tr>";
        $report_file_manager .= "<tr>";
        $report_file_manager .= "<td align='right'>Soft&nbsp;MaxDocs:</td><td><input id='service_soft_maxdocs' type='number' value='' step='100000' /></td>";
        $report_file_manager .= "<td align='right'>Index Size bytes:</td><td><input id='total_index_size_bytes' type='number' value='' step='10000000' /></td>";
        $report_file_manager .= "<td align='right'>Unanswers precent crit (5min):</td><td><input id='unanswers_5min_perc_crit' type='text' value='' /></td>";
        $report_file_manager .= "</tr>";
        $report_file_manager .= "<tr>";
        $report_file_manager .= "<td align='right'>Weight:</td><td><input id='service_weight' type='number' value='' step='1' /></td>";
        $report_file_manager .= "<td align='right'>Disaster alerts:</td><td><input id='disaster_alerts' type='number' value='' step='1' /></td>";
        $report_file_manager .= "<td align='right'>ABC User Service</td><td><input id='abc_user_service', type='number', value='' /> <a id='service_abc_user_link' href='#' target='blank' style='display:none;font-size:small;'>Link</a></td>";
        $report_file_manager .= "<td align='right'>ABC Quota Service</td><td><input id='abc_quota_service', type='number', value='' /> <a id='service_abc_quota_link' href='#' target='blank' style='display:none;font-size:small;'>Link</a></td>";
        $report_file_manager .= "</tr>";
        $report_file_manager .= "<tr>";
        $report_file_manager .= "<td align='right'>Ferryman:</td><td><input id='service_ferrymans' type='text' value=''/></td>";
        $report_file_manager .= "<td></td><td></td>";
        $report_file_manager .= "<td></td><td></td>";
        $report_file_manager .= "</tr>";
        $report_file_manager .= "</table></td></tr>";
        $report_file_manager .= "<tr><td>";
        $report_file_manager .= "<table><tr align='center'>";
        foreach ($addable_service_types as $service_type)
            $report_file_manager .= "<td><input id='btn_add_" . $service_type . "_service' type='button' onclick='onClickAddSerivce(\"$service_type\")' value='Add $service_type' style='width:100%' /></td>";
        $report_file_manager .= "</tr><tr>";
        foreach ($addable_service_types as $service_type)
            $report_file_manager .= "<td><input id='btn_copy_" . $service_type . "_service' type='button' onclick='onClickCopyService(\"$service_type\")' value='Copy $service_type' style='width:100%' /></td>";
        $report_file_manager .= "</table></td>";
        $report_file_manager .= "<td align='center' valign='top'><input type='button' id='btn_submit_owners_info' data-old-name='Submit owners info' value='Loading...' disabled onclick='return onClickSubmitOwnersInfo();'></td></tr>";
        $report_file_manager .= "</tr></table></td>";
        $report_file_manager .= "<tr><td colspan=2 id='add_service_info'></td></tr>";
    }
    //Edit service
    if ($editable_service) {
        $services_datalist = "<datalist id=\"services_list\">";
        $services_list_local = get_services_list();
        foreach ($services_list_local as $service_type => $services) {
            if ($service_type == "proxy")
                continue;
            foreach ($services as $service => $link) {
                $services_datalist .= "<option value=\"$service\"></option>";
            }
        }
        $services_datalist .= "</datalist>";
        $report_file_manager .= $services_datalist;
        $report_file_manager .= "<tr><td><h3>Edit service</h3><div id='edit_service'>Loading...";
        $report_file_manager .= "</div></td></tr>";
        $report_file_manager .= "<tr><td id='edit_service_info'></td></tr>";
    }

    //Edit configs
    $report_file_manager .= "<tr><td><h3>Edit configs</h3>";
    $report_file_manager .= "<table width='100%' border='1' frame='void'>";
    $report_file_manager .= "<tr><td colspan='2' id='path_text'></td></tr>";
    $report_file_manager .= "<tr><td width='20%' valign='top' id='dir_list'>Loading...</td><td valign='top'>$editor</td></tr>";
    $report_file_manager .= "</table>";
    $report_file_manager .= "</td></tr>";

    //Alerts
    $report_file_manager .= "<tr><td><h3>Alerts</h3>";
    $report_file_manager .= "<table width='100%' border='1' frame='void'>";
    $report_file_manager .= "<tr><td colspan='2' id='alerts'>";
    $report_file_manager .= "<a id='alerts_status' href='http://saas-mon.n.yandex-team.ru/alerts?service=$service_cgi' target='_blank'>Edit</a>";
    $report_file_manager .= "</td></tr>";
    $report_file_manager .= "</table>";
    $report_file_manager .= "</td></tr>";

    //Polynom converter
    $report_file_manager .= "<tr><td>$report_poly</td></tr>";
    //secret keys
    $report_file_manager .= "<tr><td>$report_keys</td></tr>";

    $report_file_manager .= "</table>";
    return $report_file_manager;
}
?>
