{% extends 'users/_base_user_detail.html' %}
{% load static %}
{% load i18n %}

{% block custom_head_css_js %}
    <link href="{% static "css/plugins/sweetalert/sweetalert.css" %}" rel="stylesheet">
    <script src="{% static "js/plugins/sweetalert/sweetalert.min.js" %}"></script>
{% endblock %}

{% block content_nav_delete_update %}
    <li class="pull-right">
        <a class="btn btn-outline {% if can_update %} btn-default {% else %} disabled {% endif %}" href="{% url 'users:user-update' pk=object.id %}"><i class="fa fa-edit"></i>{% trans 'Update' %}</a>
    </li>
    <li class="pull-right">
        <a class="btn btn-outline {% if can_delete %} btn-danger btn-delete-user {% else %} disabled {% endif %}">
            <i class="fa fa-trash-o"></i>{% trans 'Delete' %}
        </a>
    </li>
{% endblock %}

{% block content_table %}
    <div class="col-sm-8" style="padding-left: 0">
        <div class="ibox float-e-margins">
            <div class="ibox-title">
                <span class="label"><b>{{ object.name }}</b></span>
                <div class="ibox-tools">
                    <a class="collapse-link">
                        <i class="fa fa-chevron-up"></i>
                    </a>
                    <a class="dropdown-toggle" data-toggle="dropdown" href="#">
                        <i class="fa fa-wrench"></i>
                    </a>
                    <ul class="dropdown-menu dropdown-user">
                    </ul>
                    <a class="close-link">
                        <i class="fa fa-times"></i>
                    </a>
                </div>
            </div>
            <div class="ibox-content">
                <table class="table">
                    <tbody>
                    <tr class="no-borders-tr">
                        <td colspan="2">
                            <img src="{{ object.avatar_url }}" class="img-circle" width="64" height="64">
                        </td>
                    </tr>
                    <tr>
                        <td width="20%">{% trans 'Name' %}:</td>
                        <td><b>{{ object.name }}</b></td>
                    </tr>
                    <tr>
                        <td>{% trans 'Username' %}:</td>
                        <td><b>{{ object.username }}</b></td>
                    </tr>
                    <tr>
                        <td>{% trans 'Email' %}:</td>
                        <td><b>{{ object.email }}</b></td>
                    </tr>
                    {% if user.phone %}
                        <tr>
                            <td>{% trans 'Phone' %}:</td>
                            <td><b>{{ object.phone }}</b></td>
                        </tr>
                    {% endif %}
                    {% if object.wechat %}
                        <tr>
                            <td>{% trans 'Wechat' %}:</td>
                            <td><b>{{ object.wechat }}</b></td>
                        </tr>
                    {% endif %}
                    <tr>
                        <td>{% trans 'Role' %}:</td>
                        <td><b>{{ object.role_display }}</b></td>
                    </tr>
                    <tr>
                        <td>{% trans 'MFA certification' %}:</td>
                        <td><b>
                            {% if object.mfa_force_enabled %}
                                {% trans 'Force enabled' %}
                            {% elif  object.mfa_enabled%}
                                {% trans 'Enabled' %}
                            {% else %}
                                {% trans 'Disabled' %}
                            {% endif %}
                        </b></td>
                    </tr>
                    <tr>
                        <td>{% trans 'Source' %}:</td>
                        <td><b>{{ object.get_source_display }}</b></td>
                    </tr>
                    <tr>
                        <td>{% trans 'Date expired' %}:</td>
                        <td><b>{{ object.date_expired|date:"Y-m-j H:i:s" }}</b></td>
                    </tr>
                    <tr>
                        <td>{% trans 'Created by' %}:</td>
                        <td><b>{{ object.created_by }}</b></td>
                    </tr>
                    <tr>
                        <td>{% trans 'Date joined' %}:</td>
                        <td><b>{{ object.date_joined|date:"Y-m-j H:i:s" }}</b></td>
                    </tr>
                    <tr>
                        <td>{% trans 'Last login' %}:</td>
                        <td><b>{{ object.last_login|date:"Y-m-j H:i:s" }}</b></td>
                    </tr>
                    {% if object.can_update_password %}
                        <tr>
                            <td>{% trans 'Last password updated' %}:</td>
                            <td><b>{{ object.date_password_last_updated|date:"Y-m-j H:i:s" }}</b></td>
                        </tr>
                    {% endif %}
                    <tr>
                        <td>{% trans 'Comment' %}:</td>
                        <td><b>{{ object.comment }}</b></td>
                    </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    <div class="col-sm-4" style="padding-left: 0;padding-right: 0">
        <div class="panel panel-primary">
            <div class="panel-heading">
                <i class="fa fa-info-circle"></i> {% trans 'Quick modify' %}
            </div>
            <div class="panel-body">
                <table class="table">
                    <tbody>
                    <tr class="no-borders-tr">
                        <td width="50%">{% trans 'Active' %}:</td>
                        <td>
                            <span class="pull-right">
                                <div class="switch">
                                    <div class="onoffswitch">
                                        <input type="checkbox" {% if object.is_active %} checked {% endif %} {% if request.user == object %} disabled {% endif %} class="onoffswitch-checkbox" id="is_active">
                                        <label class="onoffswitch-label" for="is_active">
                                            <span class="onoffswitch-inner"></span>
                                            <span class="onoffswitch-switch"></span>
                                        </label>
                                    </div>
                                </div>
                            </span>
                        </td>
                    </tr>
                    <tr>
                        <td>{% trans 'Force enabled MFA' %}:</td>
                        <td>
                            <span class="pull-right">
                            <div class="switch">
                                <div class="onoffswitch">
                                    <input type="checkbox" class="onoffswitch-checkbox" {% if object.mfa_force_enabled %} checked {% endif %}
                                           id="force_enable_mfa">
                                    <label class="onoffswitch-label" for="force_enable_mfa">
                                        <span class="onoffswitch-inner"></span>
                                        <span class="onoffswitch-switch"></span>
                                    </label>
                                </div>
                            </div>
                            </span>
                        </td>
                    </tr>
                    <tr>
                        <td>{% trans 'Reset MFA' %}:</td>
                        <td>
                            <span class="pull-right">
                                <button type="button" class="btn btn-primary btn-xs" id="btn-reset-mfa" style="width: 54px">{% trans 'Reset' %}</button>
                            </span>
                        </td>
                    </tr>
                    {% if object.can_update_password %}
                        <tr>
                            <td>{% trans 'Send reset password mail' %}:</td>
                            <td>
                                <span class="pull-right">
                                    <button type="button" class="btn btn-primary btn-xs" {% if request.user == object %} disabled="disabled" {% endif %} id="btn-reset-password" style="width: 54px">{% trans 'Send' %}</button>
                                </span>
                            </td>
                        </tr>
                    {% endif %}
                    {% if object.can_update_ssh_key %}
                        <tr>
                            <td>{% trans 'Send reset ssh key mail' %}:</td>
                            <td>
                                <span class="pull-right">
                                    <button type="button" class="btn btn-primary btn-xs" {% if request.user == object %} disabled="disabled" {% endif %} id="btn-reset-pk" style="width: 54px;">{% trans 'Send' %}</button>
                                </span>
                            </td>
                        </tr>
                    {% endif %}
                    <tr style="{% if not unblock %}display:none{% endif %}">
                        <td>{% trans 'Unblock user' %}</td>
                        <td>
                            <span class="pull-right">
                                <button type="button" class="btn btn-primary btn-xs"  id="btn-unblock-user" style="width: 54px">{% trans 'Unblock' %}</button>
                            </span>
                        </td>
                    </tr>
                    </tbody>
                </table>
            </div>
        </div>
        {% if request.user.can_admin_current_org %}

            {% if object.can_user_current_org or object.can_admin_current_org %}
                <div class="panel panel-info">
                    <div class="panel-heading">
                        <i class="fa fa-info-circle"></i> {% trans 'User group' %}
                    </div>
                    <div class="panel-body">
                        <table class="table group_edit">
                            <tbody>
                            <form>
                                <tr>
                                    <td colspan="2" class="no-borders">
                                        <select data-placeholder="{% trans 'Join user groups' %}" id="groups_selected" class="select2" style="width: 100%" multiple="" tabindex="4">
                                            {% for group in groups %}
                                                <option value="{{ group.id }}" id="opt_{{ group.id }}" >{{ group.name }}</option>
                                            {% endfor %}
                                        </select>
                                    </td>
                                </tr>
                                <tr>
                                    <td colspan="2" class="no-borders">
                                        <button type="button" class="btn btn-info btn-small" id="btn_join_group">{% trans 'Join' %}</button>
                                    </td>
                                </tr>
                            </form>

                            {% for group in object.groups.all %}
                                <tr>
                                    <td >
                                        <b class="bdg_group" >{{ group.name }}</b>
                                    </td>
                                    <td>
                                        <button class="btn btn-danger pull-right btn-xs btn_leave_group" data-uid={{ group.id }} type="button"><i class="fa fa-minus"></i></button>
                                    </td>
                                </tr>
                            {% endfor %}
                            </tbody>
                        </table>
                    </div>
                </div>
            {% endif %}

            {% if LICENSE_VALID and LOGIN_CONFIRM_ENABLE %}
                <div class="panel panel-warning">
                    <div class="panel-heading">
                        <i class="fa fa-info-circle"></i> {% trans 'Login confirm' %}
                    </div>
                    <div class="panel-body">
                        <table class="table">
                            <tbody>
                            <form>
                                <tr>
                                    <td colspan="2" class="no-borders">
                                        <select data-placeholder="{% trans 'Reviewers' %}" id="id_assignees" class="users-select2" style="width: 100%" multiple="" tabindex="4">
                                        </select>
                                    </td>
                                </tr>
                                <tr>
                                    <td colspan="2" class="no-borders">
                                        <button type="button" class="btn btn-warning btn-small" id="btn_reviewer_confirm">{% trans 'Confirm' %}</button>
                                    </td>
                                </tr>
                            </form>
                            {% if object.get_login_confirm_setting %}
                                {% for u in object.login_confirm_setting.reviewers.all %}
                                    <tr>
                                        <td >
                                            <b class="bdg_reviewer">{{ u }}</b>
                                        </td>
                                        <td>
                                            <button class="btn btn-danger pull-right btn-xs btn-leave-reviewer" data-uid={{ u.id }} type="button"><i class="fa fa-minus"></i></button>
                                        </td>
                                    </tr>
                                {% endfor %}
                            {% endif %}
                            </tbody>
                        </table>
                    </div>
                </div>
            {% endif %}

        {% endif %}
    </div>

{% include 'users/_user_update_pk_modal.html' %}

{% endblock %}

{% block custom_foot_js %}
<script>
var usersSelect2;

function updateUserLoginReviewer(reviewers) {
    var url = "{% url 'api-auth:login-confirm-setting-update' user_id=object.id %}";
    var data = {reviewers: reviewers};
    requestApi({
        url: url,
        data: JSON.stringify(data),
        method: 'PATCH',
        success: function () {
            window.location.reload();
        }
    })
}


var usersGroupsRelationUrl = "{% url 'api-users:users-groups-relation-list' %}";

function addObjects(objectsId) {
    if (!objectsId || objectsId.length === 0) {
        return
    }
    var theUrl = usersGroupsRelationUrl;
    var body = [];
    objectsId.forEach(function (v) {
        var data = {user: "{{ object.id }}"};
        data["usergroup"] = v;
        body.push(data)
    });
    requestApi({
        url: theUrl,
        body: JSON.stringify(body),
        method: "POST",
        success: reloadPage
    });
}

function removeObject(objectId) {
    if (!objectId)  {
        return
    }
    var theUrl = usersGroupsRelationUrl;
    theUrl = setUrlParam(theUrl, 'user', "{{ object.id }}");
    theUrl = setUrlParam(theUrl, 'usergroup', objectId);
    requestApi({
        url: theUrl,
        method: "DELETE",
        success: reloadPage
    });
}

$(document).ready(function() {
    $('.select2').select2();
    usersSelect2 = usersSelect2Init('.users-select2')
})
.on('click', '#is_active', function() {
    var the_url = "{% url 'api-users:user-detail' pk=object.id %}";
    var checked = $(this).prop('checked');
    var body = {
        'is_active': checked
    };
    var success = '{% trans "Update successfully!" %}';
    requestApi({
        url: the_url,
        body: JSON.stringify(body),
        success_message: success
    });
})
.on('click', '#force_enable_mfa', function() {
    {% if request.user == object %}
        toastr.error("{% trans 'Goto profile page enable MFA' %}");
        return;
    {% endif %}

    var the_url = "{% url 'api-users:user-detail' pk=object.id %}";
    var checked = $(this).prop('checked');
    var mfa_level;
    var otp_secret_key;
    if(checked){
        mfa_level = 2
    }else{
        mfa_level = 0;
        otp_secret_key = '';
    }
    var body = {
        'mfa_level': mfa_level,
        'otp_secret_key': otp_secret_key
    };
    var success = '{% trans "Update successfully!" %}';
    requestApi({
        url: the_url,
        body: JSON.stringify(body),
        success_message: success
    });
 })
.on('click', '#btn_join_group', function() {
    var objectsId = $("#groups_selected").val();
    addObjects(objectsId);
}).on('click', '.btn_leave_group', function() {
    var objectId = $(this).data('uid');
    removeObject(objectId)
}).on('click', '#btn-reset-password', function() {
    function doReset() {
        var the_url = '{% url "api-users:user-reset-password" pk=object.id %}';
        var body = {};
        var success = function() {
            var msg = "{% trans "An e-mail has been sent to the user`s mailbox." %}";
            swal("{% trans 'Reset password' %}", msg, "success");
        };
        requestApi({
            url: the_url,
            body: JSON.stringify(body),
            success: success
        });
    }
    swal({
        title: "{% trans 'Are you sure?' %}",
        text: "{% trans "This will reset the user password and send a reset mail"%}",
        type: "warning",
        showCancelButton: true,
        cancelButtonText: "{% trans 'Cancel' %}",
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "{% trans 'Confirm' %}",
        closeOnConfirm: false
    }, function() {
        doReset();
    });
}).on('click', '#btn-reset-pk', function() {
    function doReset() {
        var the_url = '{% url "api-users:user-public-key-reset" pk=object.id %}';
        var body = {};
        var success = function() {
            var msg = "{% trans 'The reset-ssh-public-key E-mail has been sent successfully. Please inform the user to update his new ssh public key.' %}";
            swal("{% trans 'Reset SSH public key' %}", msg, "success");
        };
        requestApi({
            url: the_url,
            body: body,
            success: success
        });
    }
    swal({
        title: "{% trans 'Are you sure?' %}",
        text: "{% trans 'This will reset the user public key and send a reset mail' %}",
        type: "warning",
        showCancelButton: true,
        cancelButtonText: "{% trans 'Cancel' %}",
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "{% trans 'Confirm' %}",
        closeOnConfirm: false
    }, function() {
        doReset();
    });
}).on('click', '#btn-user-update-pk', function(){
    var $this = $(this);
    var pk = $('#txt_pk').val();
    var the_url = '{% url "api-users:user-public-key-reset" pk=user.id %}';
    var body = {'_public_key': pk};
    var success = function() {
        $('#txt_pk').val('');
        $this.closest('.modal').modal('hide');
        var msg = "{% trans 'Successfully updated the SSH public key.' %}";
        swal("{% trans 'User SSH public key update' %}", msg, "success");
    };
    var fail = function(msg) {
        swal({
            title: "{% trans 'User SSH public key update' %}",
            text: msg,
            type: "error",
            showCancelButton: false,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "{% trans 'Confirm' %}",
            closeOnConfirm: true
            }, function () {
              $('#txt_pk').focus();
            }
        );
    };
    requestApi({ url: the_url, body: JSON.stringify(body), success: success, error: fail});
}).on('click', '.btn-delete-user', function () {
    var $this = $(this);
    var name = "{{ object.name }}";
    var uid = "{{ object.id }}";
    var the_url = '{% url "api-users:user-detail" pk=DEFAULT_PK %}'.replace('{{ DEFAULT_PK }}', uid);
    var redirect_url = "{% url 'users:user-list' %}";
    objectDelete($this, name, the_url, redirect_url);
}).on('click', '#btn-unblock-user', function () {
    function doReset() {
        {#var the_url = '{% url "api-users:user-reset-password" pk=object.id %}';#}
        var the_url = '{%  url "api-users:user-unblock" pk=object.id %}';
        var body = {};
        var success = function() {
            var msg = "{% trans "Success" %}";
            {#swal("{% trans 'Unblock user' %}", msg, "success");#}
            swal({
                title: "{% trans 'Unblock user' %}",
                text: msg,
                type: "success"
                }, function() {
                    location.reload()
                }
            );
        };
        requestApi({
            url: the_url,
            body: JSON.stringify(body),
            success: success
        });
    }
    swal({
        title: "{% trans 'Are you sure?' %}",
        text: "{% trans "After unlocking the user, the user can log in normally."%}",
        type: "warning",
        showCancelButton: true,
        cancelButtonText: "{% trans 'Cancel' %}",
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "{% trans 'Confirm' %}",
        closeOnConfirm: false
    }, function() {
        doReset();
    });
}).on('click', '#btn-reset-mfa', function () {
    requestApi({
        url: "{% url 'api-users:user-reset-otp' pk=object.id %}",
        method: "GET",
        success_message: "{% trans 'Reset user MFA success' %}"
    })
}).on('click', '.btn-leave-reviewer', function () {
    var reviewersId = [];
    var removeReviewerId = $(this).data('uid');
    $('.btn-leave-reviewer').each(function (i, v) {
        var reviewerId = $(v).data('uid');
        if (reviewerId !== removeReviewerId) {
            reviewersId.push(reviewerId);
        }
    });
    updateUserLoginReviewer(reviewersId);
}).on('click', '#btn_reviewer_confirm', function () {
    var reviewersId = [];
    $('.btn-leave-reviewer').each(function (i, v) {
        var reviewerId = $(v).data('uid');
        reviewersId.push(reviewerId);
    });
    var selectedId = usersSelect2.val();
    if (selectedId.length === 0) {
        return
    }
    selectedId.forEach(function (i) {
        if (reviewersId.indexOf(i) === -1) {
            reviewersId.push(i)
        }
    });
    updateUserLoginReviewer(reviewersId);
})
</script>
{% endblock %}
