{% extends '_base_create_update.html' %}
{% load static %}
{% load bootstrap3 %}
{% load i18n %}
{% load asset_tags %}
{% load common_tags %}

{% block form %}
    <form action="" method="post" class="form-horizontal">
    {% if form.non_field_errors %}
         <div class="alert alert-danger">
             {{ form.non_field_errors }}
         </div>
    {% endif %}
    {% csrf_token %}
    <h3>{% trans 'Basic' %}</h3>
    {% bootstrap_field form.hostname layout="horizontal" %}
    {% bootstrap_field form.ip layout="horizontal" %}
    {% bootstrap_field form.platform layout="horizontal" %}
    {% bootstrap_field form.public_ip layout="horizontal" %}
    {% bootstrap_field form.domain layout="horizontal" %}
    <div class="hr-line-dashed"></div>

    <h3>{% trans 'Protocols' %}</h3>
    <div class="protocols">
        {% for fm in formset.forms %}
        <div class="form-group">
            <div class="col-md-2 col-md-offset-2" style="text-align: right">{{ fm.name }}</div>
            <div class="col-md-6">{{ fm.port }}</div>
            <div class="col-md-1" style="padding: 6px 0">
                <a class="btn btn-danger btn-xs btn-protocol btn-del"><span class="fa fa-minus"></span> </a>
                <a class="btn btn-primary btn-xs btn-protocol btn-add" style="display: none"><span class="fa fa-plus"></span></a>
            </div>
        </div>
        {% endfor %}
    </div>
    <div class="hr-line-dashed"></div>
    <h3>{% trans 'Auth' %}</h3>
    {% bootstrap_field form.admin_user layout="horizontal" %}

    <div class="hr-line-dashed"></div>
    <h3>{% trans 'Node' %}</h3>
    {% bootstrap_field form.nodes layout="horizontal" %}

    <div class="hr-line-dashed"></div>
    <h3>{% trans 'Labels' %}</h3>
    <div class="form-group {% if form.errors.labels %} has-error {% endif %}">
        <label for="{{ form.labels.id_for_label }}" class="col-md-2 control-label">{% trans 'Label' %}</label>
        <div class="col-md-9">
            <select name="labels" class="select2 labels" data-placeholder="{% trans 'Label' %}" style="width: 100%" multiple="" tabindex="4" id="{{ form.labels.id_for_label }}">
                {% for name, labels in form.labels.field.queryset|group_labels %}
                <optgroup label="{{ name }}">
                    {% for label in labels %}
                        {% if label in form.labels.initial %}
                            <option value="{{ label.id }}" selected>{{ label.value }}</option>
                        {% else %}
                            <option value="{{ label.id }}">{{ label.value }}</option>
                        {% endif %}
                    {% endfor %}
                </optgroup>
                {% endfor %}
            </select>
            {% if form.errors.labels %}
                {% for e in form.errors.labels %}
                    <div class="help-block">{{ e }}</div>
                {% endfor %}
            {% endif %}
        </div>
    </div>
    {% block extra %}
    {% endblock %}

    <div class="hr-line-dashed"></div>
    <h3>{% trans 'Other' %}</h3>
    {% bootstrap_field form.comment layout="horizontal" %}
    {% bootstrap_field form.is_active layout="horizontal" %}

    <div class="hr-line-dashed"></div>
    <div class="form-group">
        <div class="col-sm-4 col-sm-offset-2">
            <button class="btn btn-default" type="reset"> {% trans 'Reset' %}</button>
            <button id="submit_button" class="btn btn-primary" type="submit">{% trans 'Submit' %}</button>
        </div>
    </div>
    </form>
{% endblock %}

{% block custom_foot_js %}
<script>
var instanceId = "{{ object.id }}";
var protocolLen = 0;
function format(item) {
   var group = item.element.parentElement.label;
   return group + ':' + item.text;
}

function protocolBtnShow() {
    $(".btn-protocol.btn-add").hide();
    $(".btn-protocol.btn-add:last").show();
    var btnDel = $(".btn-protocol.btn-del");
    if (btnDel.length === 1) {
        btnDel.addClass("disabled")
    } else {
        btnDel.removeClass("disabled")
    }
}


$(document).ready(function () {
    $('.select2').select2({
        allowClear: true
    });
    $(".nodes-select2").select2({
        closeOnSelect: false,
        ajax: {
            url: '{% url "api-assets:node-list" %}',
            data: function (params) {
                var page = params.page || 1;
                var query = {
                   search: params.term,
                   offset: (page -1) * 10,
                   limit: 10
                };
                return query
            },
            processResults: function (data) {
                var results = $.map(data.results, function (v, i) {
                    return {id: v.id, text: v.full_value}
                });
                var more = !!data.next;
                console.log(more);
                return {results: results, pagination: {"more": more }}
            }
        },
    });
    $(".labels").select2({
        allowClear: true,
        templateSelection: format
    });
    $('#id_nodes.select2').select2({
        closeOnSelect: false
    });
    protocolBtnShow()
})
.on("change", "#id_platform", function () {
    if (instanceId !== "") {
        return
    }
    var platform = $(this).val();
    var protocolRef = $(".protocols").find("select").first()
    var protocol = protocolRef.val();

    var protocolShould = "";
    if (platform.startsWith("Windows")){
        protocolShould = "rdp"
    } else {
        protocolShould = "ssh"
    }
    if (protocol !== protocolShould) {
        protocolRef.val(protocolShould);
        protocolRef.trigger("change")
    }
})
.on("click", ".btn-protocol.btn-del", function () {
    $(this).parent().parent().remove();
    protocolBtnShow()
})
.on("click", ".btn-protocol.btn-add", function () {
    var protocol = "";
    var protocolsRef = $(".protocols");
    var firstProtocolForm = protocolsRef.children().first();
    var newProtocolForm = firstProtocolForm.clone();
    var protocolChoices = $.map($(firstProtocolForm.find('select option')), function (option) {
        return option.value
    });
    var protocolsSet = $.map(protocolsRef.find('select option:selected'), function(option) {
        return option.value
    });
    for (var i=0;i<protocolChoices.length;i++) {
        var p = protocolChoices[i];
        if (protocolsSet.indexOf(p) === -1) {
            protocol = p;
            break
        }
    }
    if (protocol === "") {
        return
    }
    var formNameNum = [0];
    protocolsRef.children().find("select").each(function (i, v) {
        var fieldName = $(v).attr("name");
        var num = fieldName.split('-')[1];
        formNameNum.push(parseInt(num));
    });

    var protocolLenLast = Math.max(...formNameNum);
    protocolLen = protocolLenLast + 1;
    var selectName = "form-" + protocolLen + "-name";
    var selectId = "id_" + selectName;
    var portName = "form-" + protocolLen + "-port";
    var portId = "id_" + portName;
    newProtocolForm.find("select").prop("name", selectName).prop("id", selectId);
    newProtocolForm.find("input").prop("name", portName).prop("id", portId);
    newProtocolForm.find("option[value='" + protocol + "']").attr("selected", true);
    protocolsRef.append(newProtocolForm);
    protocolLen += 1;
    $("#" + selectId).trigger("change");
    protocolBtnShow()
})
.on("change", ".protocol-name", function () {
    var name = $(this).val();
    var port = 22;
    switch (name) {
        case "ssh":
            port = 22;
            break;
        case "rdp":
            port = 3389;
            break;
        case "telnet":
            port = 23;
            break;
        case "vnc":
            port = 5901;
            break;
        default:
            port = 22;
            break
    }
    $(this).parent().parent().find(".protocol-port").val(port);
})
.on("submit", "form", function (evt) {
    evt.preventDefault();
    {% block formUrl %}
    var the_url = '{% url 'api-assets:asset-list' %}';
    var redirect_to = '{% url "assets:asset-list" %}';
    var method = "POST";
    {% endblock %}
    var form = $("form");
    var protocols = {};
    var data = form.serializeObject();
    objectAttrsIsBool(data, ['is_active']);
    objectAttrsIsList(data, ['nodes', 'labels']);
    $.each(data, function (k, v) {
        if (k.startsWith("form")){
            delete data[k];
            var _k = k.split("-");
            var formName = _k.slice(0, 2).join("-");
            var key = _k[_k.length-1];
            if (!protocols[formName]) {
                protocols[formName] = {}
            }
            protocols[formName][key] = v
        }
    });

    protocols = $.map(protocols, function (v) {
        return v.name + '/' + v.port
    });
    data["protocols"] = protocols;
    var props = {
        url: the_url,
        data: data,
        method: method,
        form: form,
        redirect_to: redirect_to
    };
    formSubmit(props);
 })
</script>
{% endblock %}
