<template>

    <Tooltip :infos="[t('version.0')]" width="8rem">
        <img class="menu-img" :src="menu_icons.extras" @click="showMenu">
    </Tooltip>

    <Drawer v-model="showVersion" width="35%">
        <UpdateLog />
    </Drawer>

    <Dialog :title="t('update.0')" v-model="showUpdate" top="5rem" left="5rem">
        <div class="nitofy">
            <div class="confirm">{{ t('update.1') }}</div>
            <div class="msg" v-if="message">{{ message }}</div>
            <div class="btns">
                <button class="button" @click="refresh">{{ t('update.2') }}</button>
                <button class="button" @click="showUpdate = false">{{ t('update.3') }}</button>
            </div>
        </div>
    </Dialog>
</template>

<script lang="ts" setup>
import { useStore } from "vuex";
import { onBeforeUnmount, onMounted, ref, computed } from "vue";
import { useI18n } from "vue3-i18n";
import { openWebSocket, registerHandler } from "@/tool/websocket";
import Dialog from "@/components/dialog.vue";
import { Tooltip, Drawer } from "@/components";
import { menu_icons } from "@/config";
import { uuid } from "@/tool";
import UpdateLog from "./update-log.vue";

const { t } = useI18n();
const { state, commit, dispatch } = useStore();
const showUpdate = ref(false);
const showVersion = computed(() => {
    return state.curMenu == 'version';
});
const message = ref('');

let url = 'ws://' + window.location.host;
if (process.env.VUE_APP_BASE_URL) {
    url = 'ws://' + process.env.VUE_APP_BASE_URL.substring(7);
}
url += '/websocket/' + uuid();
openWebSocket(url);

const refresh = () => {
    dispatch('saveGame');
    window.location.reload();
}

const onUpdate = (msg) => {
    message.value = msg;
    showUpdate.value = true;
}
registerHandler('update', 'version', onUpdate)

const showMenu = () => {
    state.curMenu = showVersion.value ? null : 'version';
}

const keydown = (e) => {
    if (e.keyCode == 86 && !e.ctrlKey) {
        showMenu();
    }
}

onMounted(() => {
    document.addEventListener('keydown', keydown);
});
onBeforeUnmount(() => {
    document.removeEventListener('keydown', keydown);
})
</script>
<style lang="scss" scoped>
.nitofy {
    width: 25rem;
    padding: 0.5rem;
}

.confirm {
    width: 100%;
    font-size: 1.2rem;
    text-align: start;
}

.msg {
    color: #d1cfcf;
    width: 100%;
    white-space: normal;
    word-break: break-all;
    overflow: hidden;
    padding: 1rem;
}
</style>