<template>
    <XModalWindow
        ref="dialog"
        :width="400"
        :height="450"
        :with-ok-button="true"
        :ok-button-disabled="false"
        @ok="ok()"
        @close="dialog?.close()"
        @closed="emit('closed')"
    >
        <template #header>{{ i18n.ts.notificationSetting }}</template>
        <div class="_monolithic_">
            <div v-if="showGlobalToggle" class="_section">
                <MkSwitch v-model="useGlobalSetting">
                    {{ i18n.ts.useGlobalSetting }}
                    <template #caption>{{
                        i18n.ts.useGlobalSettingDesc
                    }}</template>
                </MkSwitch>
            </div>
            <div v-if="!useGlobalSetting" class="_section">
                <MkInfo>{{ i18n.ts.notificationSettingDesc }}</MkInfo>
                <MkButton inline @click="disableAll">{{
                    i18n.ts.disableAll
                }}</MkButton>
                <MkButton inline @click="enableAll">{{
                    i18n.ts.enableAll
                }}</MkButton>
                <MkSwitch
                    v-for="ntype in notificationTypes"
                    :key="ntype"
                    v-model="typesMap[ntype]"
                    >{{ i18n.t(`_notification._magTypes.${ntype}`) }}</MkSwitch
                >
            </div>
        </div>
    </XModalWindow>
</template>

<script lang="ts" setup>
import { computed, ref } from "vue";
import MkSwitch from "./form/switch.vue";
import MkInfo from "./MkInfo.vue";
import MkButton from "./MkButton.vue";
import XModalWindow from "@/components/MkModalWindow.vue";
import { i18n } from "@/i18n";
import { notificationTypes, types } from "magnetar-common";

const emit = defineEmits<{
    done: [{ includingTypes: types.NotificationType[] | null }];
    closed: [];
}>();

const props = withDefaults(
    defineProps<{
        includingTypes?: types.NotificationType[] | null;
        showGlobalToggle?: boolean;
    }>(),
    {
        includingTypes: () => notificationTypes,
        showGlobalToggle: true,
    },
);

let includingTypes = computed(() => props.includingTypes || []);

const dialog = ref<InstanceType<typeof XModalWindow>>();

let typesMap = ref(
    Object.fromEntries(
        notificationTypes.map((n) => [n, includingTypes.value.includes(n)]),
    ) as Record<types.NotificationType, boolean>,
);

let useGlobalSetting = ref(includingTypes === null || props.showGlobalToggle);

function ok() {
    if (useGlobalSetting) {
        emit("done", { includingTypes: null });
    } else {
        emit("done", {
            includingTypes: notificationTypes.filter((type) => typesMap[type]),
        });
    }

    dialog.value?.close();
}

function disableAll() {
    for (const type in typesMap) {
        typesMap[type as types.NotificationType] = false;
    }
}

function enableAll() {
    for (const type in typesMap) {
        typesMap[type as types.NotificationType] = true;
    }
}
</script>
