<!-- ============================================================== -->
<!-- User Modal Content -->
<!-- ============================================================== -->
{% set readonly = '' if current_user.is_manager else 'readonly' %}
{% set disabled = '' if current_user.is_manager else 'disabled' %}

  <div class="modal-dialog modal-dialog-centered modal-xl" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h3 class="modal-title" id="user-modal-title"> User (id = {{ user.id }}) </h3>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">

            <!-- User Form -->
            <form id="user-form" data-parsley-validate="" novalidate="">
            <div class="row">
            <div class="col-xl-2 col-lg-2 col-md-2 col-sm-2 col-2">
                <div id="profile-container">
                   <img id="user-profile-image" name="user-profile-image" src="{{ user.image }}" />
                </div>
                <input id="imageUpload" type="file"
                       name="profile_photo" placeholder="Photo" required="" capture>
            </div>

            <div class="col-xl-10 col-lg-10 col-md-10 col-sm-10 col-10">

                    <input type="hidden" id="user-id" name="user-id" value="{{ user.id }}">

                    <!-- Created Row -->
                    <div class="form-group row">
                        <label class="col-12 col-sm-3 col-form-label text-sm-right">Created</label>
                        <label class="col-12 col-sm-8 col-form-label text-sm-left">{{ user.created|pretty_datetime }}</label>
                    </div>

                    <!-- Username Row -->
                    <div class="form-group row">
                        <label class="col-12 col-sm-3 col-form-label text-sm-right">Username</label>
                        <label class="col-12 col-sm-8 col-form-label text-sm-left">{{ user.username }}</label>
                    </div>

                    <!-- Email Row -->
                    <div class="form-group row">
                        <label class="col-12 col-sm-3 col-form-label text-sm-right">Email</label>
                        <label class="col-12 col-sm-8 col-form-label text-sm-left">{{ user.email }}</label>
                    </div>

                    <!-- Status Row -->
                    <div class="form-group row">
                        <label class="col-12 col-sm-3 col-form-label text-sm-right">Status</label>
                        <div class="col-12 col-sm-8 col-form-label text-sm-left">
                            <select id="user-status-select" name="user-status-select", class="selectpicker">
                                {% for s in user_statuses %}
                                    {% set selected = 'selected' if user.status == s else '' %}
                                    <option value="{{ s }}" {{ selected }}>{{ s }} </option>
                                {% endfor %}
                            </select>
                        </div>
                    </div>

                    <!-- Name Row -->
                    <div class="form-group row">
                        <label class="col-12 col-sm-3 col-form-label text-sm-right">Name</label>
                        <div class="col-12 col-sm-8 col-lg-6">
                            <input type="text" required="" placeholder="Enter username" id="user-name" name="user-name" class="form-control" value="{{ user.name }}">
                        </div>
                    </div>

                    <!-- Phone Row -->
                    <div class="form-group row">
                        <label class="col-12 col-sm-3 col-form-label text-sm-right">Phone</label>
                        <div class="col-12 col-sm-8 col-lg-6">
                            <input type="text" required="" placeholder="Enter phone" id="user-phone" name="user-phone" class="form-control" value="{{ user.phone }}">
                        </div>
                    </div>

                    <!-- New Password Row -->
                    <div class="form-group row">
                        <label class="col-12 col-sm-3 col-form-label text-sm-right">New Password</label>
                        <div class="col-12 col-sm-8 col-lg-6">
                            <input type="password" required="" placeholder="Enter new password" id="user-password" name="user-password" class="form-control" value="">
                        </div>
                    </div>
                    <!-- New Password Repeat Row -->
                    <div class="form-group row">
                        <label class="col-12 col-sm-3 col-form-label text-sm-right">Repeat new password</label>
                        <div class="col-12 col-sm-8 col-lg-6">
                            <input type="password" required="" placeholder="Repeat new password" id="user-repeat-password" name="user-repeat-password" class="form-control" value="">
                        </div>
                    </div>

                    <!-- Roles -->
                    <div class="form-group row">
                        <label class="col-12 col-sm-3 col-form-label text-sm-right">Roles</label>

                        <div class="col-12 col-sm-8 col-lg-6">
                            {% for role_key, role_value in user.rolesmap.items() %}
                                {% set checked = 'checked=""' if role_value else '' %}
                                <label class="custom-control custom-checkbox custom-control-inline">
                                    <input type="checkbox" name="role-{{ role_key }}"{{ checked }} class="custom-control-input" {{ disabled }}>
                                    <span class="custom-control-label">{{ role_key }}</span>
                                </label>
                            {% endfor %}
                        </div>
                    </div>

                    <!-- PI -->
                    <div class="form-group row">
                        <label class="col-12 col-sm-3 col-form-label text-sm-right">PI</label>
                        <div class="col-12 col-sm-8 col-lg-6">
                            {% if possible_pis %}
                                <select id="user-pi-select" name="user-pi-select" class="selectpicker show-tick" data-width="100%" data-live-search="true">
                                    <option value="0"></option>
                                    {% for pi in possible_pis %}
                                        {% set selected = 'selected' if pi['id'] == user.pi.id else '' %}
                                        <option value="{{pi['id']}}" {{ selected }}>{{pi['name']}}</option>
                                    {% endfor %}
                                </select>
                            {% else %}
                                <input type="text" id="user-pi-text" class="form-control" value="{{ pi_label }}" readonly>
                            {% endif %}
                        </div>
                    </div>
            </div>

                </div>
            </form>

        <!-- end User Form -->
      </div>

      <div class="modal-footer">
          {% if current_user.is_manager or current_user.id == user.id %}
            <button type="button" id="user-btn-cancel"  class="btn btn-outline-secondary" data-dismiss="modal">Cancel</button>
            <button type="button" id="user-btn-ok" class="btn btn-outline-dark" onclick="javascript: onUserOkButtonClick()">Update</button>
          {% else %}
              <button type="button" id="user-btn-ok"  class="btn btn-outline-secondary" data-dismiss="modal">OK</button>
          {% endif %}
      </div>
    </div>
  </div>
<!-- ============================================================== -->
<!-- End of User Modal Content -->
<!-- ============================================================== -->

<script>

(function(window, document, $, undefined) {
"use strict";

    $("#user-profile-image").click(function(e) {
        $("#imageUpload").click();
    });

    function fasterPreview( uploader ) {
        if ( uploader.files && uploader.files[0] ){
            // Validate max image size
            if (uploader.files[0].size > 1024 * 1024){
                showMessage('ERROR', "Images over 1 Mb are not allowed!");
            }
            else {
                $('#user-profile-image').attr('src',
                    window.URL.createObjectURL(uploader.files[0]));
            }
        }
    }

    $("#imageUpload").change(function(){
        fasterPreview( this );
    });

    $('select').selectpicker();

})(window, document, window.jQuery);


/** Helper functions to handle User AJAX response or failure */
function handleUserAjaxDone(jsonResponse) {
    var error = null;

    if ('user' in jsonResponse) {
    }
    else if ('error' in jsonResponse) {
        error = jsonResponse.error;
    }
    else {
        error = 'Unexpected response from server.'
    }

    if (error)
        showMessage('ERROR', error);
    else {
        showMessage('SUCCESS', 'User updated successfully.');
        $('#user-modal').modal('hide');
    }
}


function handleAjaxFail(jqXHR, textStatus) {
    showMessage("ERROR", "Request failed: " + textStatus );
}


/** This function will be called when the OK button in the User form
 * is clicked. It can be either Create or Update action.
 */
function onUserOkButtonClick() {
    var frm = $('#user-form');
    var formData = new FormData(frm[0]);
    var uploader = $('input[type=file]')[0];
    if ( uploader.files && uploader.files[0] ){
        formData.append('user-profile-image', uploader.files[0]);
    }

    // Validate passwords match
    password = $('#user-password').val();
    repeat_password = $('#user-repeat-password').val();

    if (password !== repeat_password) {
        showMessage('ERROR', 'Please type same password twice!');
        return;
    }

    if (/\s/g.test(password)){
        showMessage('ERROR', 'Password can not contains spaces');
        return;
    }

    var ajaxContent = $.ajax({
        url: "{{ url_for('api.update_user_form') }}",
        type: "POST",
        data: formData,
        processData: false,
        contentType: false,
        dataType: "json"
    });
    ajaxContent.done(handleUserAjaxDone);
    ajaxContent.fail(handleAjaxFail);
}  // function onUserOkButtonClick
</script>
