@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@model PSTW_CentralSystem.Models.ModuleSettingModel
@{
    ViewData["Title"] = "Module Setting";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<div class="row" id="app">
    <div class="col-md-12 col-lg-12">
        <div class="card">
            <div class="card-body">
                <div class="col-md-12 col-lg-12">
                    <div v-if="moduleData">
                        <form v-on:submit.prevent="">
                            <div class="card">
                                <div class="card-body">
                                    <h5 class="card-title">Settings</h5>
                                    <div class="form-group row">
                                        <label class="col-md-3 mt-3">Module Name</label>
                                        <div class="col-md-6">
                                            <input type="text" class="form-control" name="moduleName" :value="moduleData.moduleName" readonly />
                                        </div>
                                    </div>
                                    <div class="form-group row">
                                        <label class="col-md-3 mt-3">Module Access</label>
                                        <div class="col-md-6">
                                            <select class="form-select shadow-none mt-3" name="allowedUserType" v-model="moduleData.allowedUserType" style="height: 36px; width: 100%">
                                                <optgroup label="General">
                                                    <option value="Public">Public</option>
                                                    <option value="Registered User">Registered User</option>
                                                </optgroup>
                                                <optgroup label="Role">
                                                    <option v-for="(roleType, index) in roleData" :key="index" :value="roleType.name">{{ roleType.name }}</option>
                                                </optgroup>
                                            </select>
                                        </div>
                                    </div>
                                    <div v-show="moduleData && moduleData.allowedUserType == 'Registered User'">
                                        <div class="form-group row">
                                            <label class="col-md-3 mt-3">Available Method</label>
                                            <div class="col-md-3">
                                                <select class="form-select shadow-none mt-3" name="allowedUserType" v-model="selectedModule" style="height: 36px; width: 100%">
                                                    <option v-for="(methods, index) in availableMethod" :key="index" :value="methods">{{ methods }}</option>
                                                </select>
                                            </div>
                                            <button class="btn col-md-3 f-icon mt-3 d-flex align-items-center" style="height: 36px; width: auto" v-on:click="addMethod(selectedModule)">
                                                <i class=" fas fa-plus-square fa-lg"></i>&ensp;Add method
                                            </button>
                                        </div>
                                        <div class="form-group row">
                                            <label class="col-md-3 mt-3">Add Method Rules</label>
                                            <div class="col-md-9">
                                                <ul class="nav nav-tabs" role="tablist">
                                                    <li class="nav-item" role="presentation" v-for="(setMethod, index) in moduleData.methodAllowedUserType" :key="index">
                                                        <a :class="['nav-link', activeTab === index ? 'active' : '']"
                                                           :id="'simple-tab-' + index"
                                                           data-bs-toggle="tab"
                                                           :href="'#simple-tabpanel-' + index"
                                                           role="tab"
                                                           :aria-controls="'simple-tabpanel-' + index"
                                                           :aria-selected="activeTab === index ? 'true' : 'false'">
                                                            {{ setMethod.methodName }}
                                                        </a>
                                                    </li>
                                                </ul>
                                                <div class="tab-content pt-5" id="tab-content">
                                                    <div :class="['tab-pane', activeTab === index ? 'active' : '']" :id="'simple-tabpanel-' + index" role="tabpanel" :aria-labelledby="'simple-tab-' + index" v-for="(setMethod, index) in moduleData.methodAllowedUserType" :key="index">
                                                        <p>Tab {{ setMethod.methodName }} selected</p>
                                                        <div class="form-group row">
                                                            <label class="col-md-1">Role:</label>
                                                            <div class="col-md-6">
                                                                <select class="select2 form-select shadow-none mt-3" multiple="multiple" style="height: 36px; width: 100%" v-model="moduleData.methodAllowedUserType[index].allowedUserTypesArray">
                                                                    <option v-for="(roleType, index) in roleData" :key="index" :value="roleType.name">{{ roleType.name }}</option>
                                                                </select>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="border-top">
                                    <div class="card-body" v-on:click="saveData">
                                        <button type="button" class="btn btn-primary">
                                            Save
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                    <div v-else><p>... Loading</p></div>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- MODAL -->
<div class="modal fade" id="confirm-dialog" tabindex="-1" role="dialog" aria-labelledby="confirm-dialog-title" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="confirm-dialog-title">Confirmation</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div v-if="selectedModule">
                <div class="modal-body">
                    <p>Are you sure you want to delete module {{ selectedModule.moduleName }}?</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <input type="hidden" id="delete-id">
                    <a id="confirmButton" href="#" class="btn btn-danger" v-on:click="confirmDelete(selectedModule)">Confirm</a>
                </div>
            </div>
            <div v-else><p>Loading...</p></div>
        </div>
    </div>
</div>
@section Scripts {
    @{
        await Html.RenderPartialAsync("_ValidationScriptsPartial");
    }
    <script>
        const app = Vue.createApp({
            data() {
                return {
                    moduleData: null,
                    roleData: null,
                    controllerMethodData: null,
                    activeTab: null,
                    availableMethod: [],
                    selectedModule: null
                };
            },
            mounted() {
                this.fetchXModule();
                this.fetchControllerMethodList();
            },
            watch: {
                // Watching allowedUserType directly
                // 'moduleData.allowedUserType'(newVal, oldVal) {
                //     console.log(`allowedUserType changed from ${oldVal} to ${newVal}`);
                // }
                'moduleData.allowedUserType'(newVal, oldVal) {
                    // console.log(`allowedUserType changed from ${oldVal} to ${newVal}`);
                    this.filterAvailableMethods();
                }
            },
            methods: {
                fetchXModule() {
                    var id = @Model.SettingId
                        fetch('/ModuleAPI/GetXModuleInformation?id=' + id, {
                            method: 'POST'
                        })
                            .then(response => response.json())
                            .then(data => {
                                console.log(data);
                                if (data != null) {
                                    this.moduleData = data;

                                    this.fetchRoleList();
                                }
                            })
                            .catch(error => {
                                console.error('There was a problem with the fetch operation:', error);
                            });
                },
                fetchRoleList() {
                    fetch('/RoleAPI/GetRoleList', {
                        method: 'POST'
                    })
                        .then(response => response.json())
                        .then(data => {
                            console.log(data);
                            if (data != null) {
                                this.roleData = data;
                                this.$nextTick(() => {
                                    $(".select2").select2().on("change", (event) => {
                                        const index = $(event.target).closest('.tab-pane').index();
                                        this.moduleData.methodAllowedUserType[index].allowedUserTypesArray = $(event.target).val();
                                    });
                                });
                            }
                        })
                        .catch(error => {
                            console.error('There was a problem with the fetch operation:', error);
                        });
                },
                fetchControllerMethodList() {
                    var moduleName = '@Model.ModuleName'
                    fetch('/AdminAPI/GetClassAndMethodInformation?moduleName=' + moduleName, {
                        method: 'POST'
                    })
                        .then(response => response.json())
                        .then(data => {
                            console.log(data);
                            if (data != null) {
                                this.controllerMethodData = data;
                            }
                        })
                        .catch(error => {
                            console.error('There was a problem with the fetch operation:', error);
                        });
                },
                deleteModule(module) {
                    this.selectedModule = module; // Set selected user
                    $('#confirm-dialog').modal('show'); // Show the modal
                },
                confirmDelete(module) {
                    fetch('/ModuleAPI/DeleteModule/' + module.settingId, {
                        method: 'POST'
                    })
                        .then(response => {
                            if (!response.ok) {
                                throw new Error('Failed to delete module');
                            }
                            // Remove the deleted user from the userData array
                            const index = this.moduleData.findIndex(u => u.settingId === module.settingId);
                            if (index !== -1) {
                                alert("Module deleted successfully");
                                this.moduleData.splice(index, 1);
                            }
                            $('#confirm-dialog').modal('hide'); // Hide the modal after deletion
                        })
                        .catch(error => {
                            console.error('Failed to delete module with status:', error);
                        });
                },
                addMethod(module) {
                    var id = @Model.SettingId;
                    fetch('/ModuleAPI/addMethod?id=' + id + '&module=' + encodeURIComponent(module), {
                        method: 'POST'
                    })
                        .then(response => {
                            if (!response.ok) {
                                throw new Error('HTTP error! status: ' + response.status);
                            }
                            return response.json();
                        })
                        .then(data => {
                            console.log('Method added successfully:', data);
                            alert('Method added successfully');
                            this.fetchXModule(); // Refresh the module data
                        })
                        .catch(error => {
                            console.error('There was a problem when adding the module operation:', error);
                            alert('Failed to add method: ' + error.message);
                        });
                },
                saveData() {
                    fetch('/ModuleAPI/saveData', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(this.moduleData)
                    })
                        .then(response => {
                            if (!response.ok) {
                                throw new Error('Failed to save module information');
                            }
                            alert('Module information saved successfully');
                        })
                        .catch(error => {
                            console.error('There was a problem with the update operation:', error);
                            alert('Failed to save data: ' + error.message);
                        });
                },

                filterAvailableMethods() {
                    const moduleMethods = this.moduleData.methodAllowedUserType.map(method => method.methodName);
                    this.availableMethod = this.controllerMethodData.methods.filter(method => !moduleMethods.includes(method)); // exclude methods that are already in moduleMethods
                },
            },
        })
        $(function () {
            app.mount('#app');
        });
    </script>
}
