<!--
 ~ Copyright 2022 youngmonkeys.org
 ~ 
 ~ Licensed under the ezyplatform, Version 1.0.0 (the "License");
 ~ you may not use this file except in compliance with the License.
 ~ You may obtain a copy of the License at
 ~ 
 ~     https://youngmonkeys.org/licenses/ezyplatform-1.0.0.txt
 ~ 
 ~ Unless required by applicable law or agreed to in writing, software
 ~ distributed under the License is distributed on an "AS IS" BASIS,
 ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 ~ See the License for the specific language governing permissions and
 ~ limitations under the License.
-->

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<body>
<div th:fragment="content" class="modal fade pt-4rem" id="add-setting">
    <div class="modal-dialog modal-md">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">[[#{add_new_setting}]]</h4>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="addSettingForm" onsubmit="return false;">
                    <div class="form-group row">
                        <label for="addSettingName" class="col-2 col-form-label">[[#{name}]]:</label>
                        <div class="col-10">
                            <label class="col-form-label text-danger d-none" id="addSettingNameErrorLabel" for="addSettingName">
                                <i class="far fa-times-circle"></i> <span id="addSettingNameError"></span>
                            </label>
                            <input type="text" name="name" id="addSettingName"
                                   class="form-control" th:placeholder="#{name}"
                                   onkeydown="ezyadmin.onKeyDownToSaveSetting('add')">
                        </div>
                    </div>
                    <div class="form-group row">
                        <label for="addSettingDataType" class="col-2 col-form-label">
                            [[#{type}]]:
                        </label>
                        <div class="col-10">
                            <label class="col-form-label text-danger d-none" id="addSettingDataTypeErrorLabel" for="addSettingDataType">
                                <i class="far fa-times-circle"></i> <span id="addSettingDataTypeError"></span>
                            </label>
                            <select name="dataType" id="addSettingDataType" class="form-control" aria-label="Type Select"
                                    onchange="ezyadmin.onSettingValueTypeChanged(this, 'add');">
                                <option value="" selected>[[#{select_a_type}]]</option>
                                <option th:each="dataType : ${dataTypes}"
                                        th:value="${dataType}">
                                    [[#{${dataType.toLowerCase()}}]]
                                </option>
                            </select>
                        </div>
                    </div>
                    <div class="form-group row mb-0">
                        <label for="addSettingValue" class="col-2 col-form-label">[[#{value}]]:</label>
                        <div class="col-10">
                            <label class="col-form-label text-danger d-none" id="addSettingValueErrorLabel" for="addSettingValue">
                                <i class="far fa-times-circle"></i> <span id="addSettingValueError"></span>
                            </label>
                            <textarea name="value" id="addSettingValue"
                                      class="form-control" th:placeholder="#{value}" rows="3"></textarea>
                            <div class="input-group cursor-pointer d-none" id="addSettingImageGroup" onclick="ezyadmin.selectSettingMedia('add', 'image');">
                                <input type="text" name="settingImage"
                                       id="addSettingImage" class="form-control" th:placeholder="#{select_an_image}">
                                <div class="input-group-append">
                                    <div class="input-group-text">
                                        <span>[[#{browse}]]</span>
                                    </div>
                                </div>
                            </div>
                            <div class="input-group cursor-pointer d-none" id="addSettingMediaGroup" onclick="ezyadmin.selectSettingMedia('add', 'media');">
                                <input type="text" name="settingMedia"
                                       id="addSettingMedia" class="form-control" th:placeholder="#{select_a_media}">
                                <div class="input-group-append">
                                    <div class="input-group-text">
                                        <span>[[#{browse}]]</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="form-group row mt-2">
                        <label for="addChangeLastUpdateTime" class="col-2 col-form-label">
                            [[#{include}]]:
                        </label>
                        <div class="col-10 d-flex align-items-center">
                            <input type="checkbox" name="changeLastUpdateTime" id="addChangeLastUpdateTime" class="form-check wh-1rem">
                            <span class="ml-1">[[#{last_update_time_of_this_setting}]]</span>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer justify-content-between">
                <div>
                    <button type="button" class="btn btn-default" data-dismiss="modal"
                            onclick="ezyadmin.resetAddSettingModel();">[[#{cancel}]]</button>
                    <button type="button" class="btn btn-default ml-2"
                            onclick="ezyadmin.resetAddSettingModel();">[[#{reset}]]</button>
                </div>
                <button type="button" class="btn btn-primary" onclick="ezyadmin.addNewSetting();">[[#{add}]]</button>
            </div>
        </div>
        <!-- /.modal-content -->
    </div>
    <!-- /.modal-dialog -->
</div>
<script th:fragment="scripts">
// ========== setting modal init =============
ezyadmin.onKeyDownToSaveSetting = function(action) {
    if(event.key === 'Enter') {
        ezyadmin.saveSetting(action);
    }
}

ezyadmin.selectSettingMedia = function(action, mediaType) {
    ezyadmin.currentSettingAction = action;
    $(`#${action}-setting`).modal('hide');
    ezyadmin.showMediaModal(mediaType)
        .onMediaShow(media => {
            if (mediaType == 'image' && media.type != 'IMAGE') {
                $('#selectMediaButton').attr('disabled', true);
            }
        })
        .onMediaSelected(media => {
            ezyadmin.onSettingMediaSelected(action, mediaType, media);
        });
}

ezyadmin.onSettingMediaSelected = function(action, mediaType, media) {
    var elementId = `#${action}Setting${mediaType[0].toUpperCase()}${mediaType.substring(1)}`;
    $(elementId).val(ezyadmin.extractMediaUrl(media));
    ezyadmin.closeMediaModal();
    $(`#${action}-setting`).modal('show');
}

$("#media-modal").on("hidden.bs.modal", function () {
    $(`#${ezyadmin.currentSettingAction}-setting`).modal('show');
});

ezyadmin.onSettingValueTypeChanged = function(e, action) {
    var dataType = $(e).val();
    $(`#${action}SettingValue`).addClass('d-none');
    $(`#${action}SettingMediaGroup`).addClass('d-none');
    $(`#${action}SettingImageGroup`).addClass('d-none');
    if (dataType == 'IMAGE') {
        $(`#${action}SettingImageGroup`).removeClass('d-none');
    } else if (dataType == 'MEDIA') {
        $(`#${action}SettingMediaGroup`).removeClass('d-none');
    } else {
        var inputType = ezyadmin.dataTypeToInputType(dataType);
        $(`#${action}SettingValue`)
            .attr('type', inputType)
            .removeClass('d-none');
    }
}

ezyadmin.dataTypeToInputType = function(dataType) {
    var inputType = 'text';
    if (dataType == 'PASSWORD' || dataType == 'EMAIL') {
        inputType = dataType.toLowerCase();
    }
    return inputType;
}

ezyadmin.saveSetting = function(action) {
    var data = ezyadmin.formDataToObject(`${action}SettingForm`);
    if (data.dataType == 'IMAGE') {
        data.value = data.settingImage;
    } else if (data.dataType == 'MEDIA') {
        data.value = data.settingMedia;
    }
    delete data.settingImage;
    delete data.settingMedia;
    var hasError = false;
    if (!data.name) {
        $(`#${action}SettingNameError`)
            .text(ezyadmin.getErrorMessageByCode('required'));
        $(`#${action}SettingNameErrorLabel`).removeClass('d-none');
        hasError = true;
    } else {
        $(`#${action}SettingNameErrorLabel`).addClass('d-none');
    }
    if (!data.dataType) {
        $(`#${action}SettingDataTypeError`)
            .text(ezyadmin.getErrorMessageByCode('required'));
        $(`#${action}SettingDataTypeErrorLabel`).removeClass('d-none');
        hasError = true;
    } else {
        $(`#${action}SettingDataTypeErrorLabel`).addClass('d-none');
    }
    if (!data.value) {
        $(`#${action}SettingValueError`)
            .text(ezyadmin.getErrorMessageByCode('required'));
        $(`#${action}SettingValueErrorLabel`).removeClass('d-none');
        hasError = true;
    } else {
        var isValidJson = true;
        if (data.dataType == 'JSON') {
            try {
                JSON.parse(data.value);
            } catch (e) {
                isValidJson = false;
            }
        }
        if (isValidJson) {
            $(`#${action}SettingValueErrorLabel`).addClass('d-none');
        } else {
            $(`#${action}SettingValueError`).text(ezyadmin.messages.invalid);
            $(`#${action}SettingValueErrorLabel`).removeClass('d-none');
            hasError = true;
        }
    }
    if (hasError) {
        return;
    }
    data.changeLastUpdateTime = $(`#${action}ChangeLastUpdateTime`)
        .prop('checked');
    $.ajax({
        type: action == 'add' ? 'POST' : 'PUT',
        url: `/api/v1/settings/${action == 'add' ? 'add' : ezyadmin.selectedSettingId}`,
        data: JSON.stringify(data),
        contentType: 'application/json',
        success: function (responseData) {
            var setting = responseData;
            if (action == 'add') {
                ezyadmin.fetchSettingList();
            } else {
                ezyadmin.fetchSettingList('current');
            }
            $(`#${action}-setting`).modal('hide');
            ezyadmin.resetAddSettingModel();
        },
        error: function (e) {
            ezyadmin.processUpdateApiErrors(data, e);
        }
    });
}

// ========== setting add =============
ezyadmin.onNewButtonClick = function(e) {
    $('#addSettingDataType').val(ezyadmin.settingSearchDataType);
    $('#add-setting').modal('show');
}

ezyadmin.resetAddSettingModel = function() {
    $('#addSettingName').val('');
    $('#addSettingValue').val('');
    $('#addSettingImage').val('');
    $('#addSettingMedia').val('');
    $('#addSettingDataType').val('').change();
}

ezyadmin.addNewSetting = function() {
    ezyadmin.saveSetting('add');
}
</script>
</body>
</html>
