<script setup>
import {onBeforeMount, ref} from "vue";
import {getCurrentWebviewWindow} from "@tauri-apps/api/webviewWindow";

import {useDark} from "@vueuse/core";
useDark();
import {invoke} from "@tauri-apps/api/core";
import ConfirmModal from "./api_components/ConfirmModal.vue";
import {listen} from "@tauri-apps/api/event";
import SettingsModal from "./api_components/SettingsModal.vue";
import PageHandler from "./api_wiki/PageHandler.vue";
const appWindow = getCurrentWebviewWindow()


let wiki_open = ref(false);

let pending = ref(true);
let api_status = ref(false);

let confirm_modal = ref(false);
let settings_modal = ref(false);

let settings_port = ref(0);
let settings_autostart = ref(true);

let input_val = ref((() => {
    let string = "";
    for(let i = 0; i < 5; i++) string += (Math.random() + 1).toString(36).substring(2);
    return string;
})())

async function get_status() {
    pending.value = true;
    await invoke('get_status')
        .then((res) => {
            api_status.value = res;
        });
}

onBeforeMount(async () => {
    await invoke('check_or_create_config_file')
        .then(async () => {
            await get_status();
            pending.value = false;
        });

    await listen('update_api', async () => {
        await get_status();
        pending.value = false;
    })
});

async function run_api() {
    await invoke('start_tcp_server');
}

async function stop_api() {
    await invoke('send_command_to_server', {
        command: "stop"
    });
}

async function open_settings() {
    await invoke('get_port')
        .then(async (res) => {
            settings_port.value = res;
            await invoke('get_autostart')
                .then((res) => {
                    settings_autostart.value = res;
                    settings_modal.value = true;
                })
        })
}

async function regen_token(){
    confirm_modal.value = false;
    await invoke('reset_token')
        .then((res) => {
            let input = document.getElementById('token_con');
            let timer = document.getElementById('timer');
            input.type = "text";
            input_val.value = res;

            let i = 15;
            timer.textContent = i.toString() + "s";

            let timerI = setInterval(() => {
                i--;
                if(i===0){
                    input_val.value = (() => {
                        let string = "";
                        for(let i = 0; i < 5; i++) string += (Math.random() + 1).toString(36).substring(2);
                        return string;
                    })();
                    input.type = "password";
                    timer.textContent = "";
                    clearInterval(timerI);
                } else{
                    timer.textContent = i.toString() + "s";
                }
            }, 1000);
        });
}

function select_input(event){
    event.target.select();
}
</script>

<template>
    <div v-if="pending">
        <img src="/icon/eos-icons--three-dots-loading.svg" alt="Loading" style="width: 96px; height: 96px" class="dark:invert absolute top-[50%] left-[50%] translate-x-[-50%] translate-y-[-50%]">
    </div>
    <div v-else>
        <slot/>
        <div v-if="!wiki_open">
            <button class="absolute top-10 right-2" @click="open_settings">
                <img src="/icon/material-symbols--settings-outline.svg" alt="API settings" style="width: 38px; height: 38px" class="dark:invert">
            </button>
            <div class="mt-8">
                <div class="mt-[28vh] grid grid-cols-1 grid-rows-3 sm:grid-cols-2 sm:grid-rows-2 gap-2.5 dark:text-white md:mx-16 lg:mx-24">
                    <div class="text-center shadow dark:shadow-white mx-4 sm:mx-0 sm:ml-4 rounded-lg p-1 row-span-1">
                        <p class="mb-4">Статус</p>
                        <div v-if="!api_status" class="flex text-center align-middle items-center">
                            <img src="/icon/api/oui--dot.svg" alt="Api status"
                                 style="width: 36px; height: 36px; filter: invert(58%) sepia(88%) saturate(5276%) hue-rotate(336deg) brightness(95%) contrast(98%);">
                            <span>Не подключено</span>
                            <button @click="run_api" class="bg-green-500 text-white rounded-lg py-1 px-2 ml-2 hover:bg-green-600 transition-colors">Запустить</button>
                        </div>
                        <div v-else class="flex text-center align-middle items-center">
                            <img src="/icon/api/oui--dot.svg" alt="Api status"
                                 style="width: 36px; height: 36px; filter: invert(69%) sepia(18%) saturate(2201%) hue-rotate(86deg) brightness(91%) contrast(77%);">
                            <span>Работает</span>
                            <button @click="stop_api" class="bg-green-500 text-white rounded-lg py-1 px-2 ml-2 hover:bg-green-600 transition-colors">Остановить</button>
                        </div>
                    </div>
                    <div class="grid text-center shadow dark:shadow-white mx-4 sm:mx-0 sm:mr-4 rounded-lg p-1 justify-center items-center row-start-2 sm:row-span-1">
                        <div v-if="api_status">
                            <p class="mb-2">Токен подключения</p>
                            <div>
                                <input @click="select_input" size="30" id="token_con" readonly type="password" class="rounded-lg my-0.5 px-2 dark:bg-zinc-700"
                                       :value="input_val">
                            </div>
                            <div class="flex justify-center items-center">
                                <button class="text-[15px] m-1 rounded-lg bg-red-500 text-white py-1 px-2" @click="confirm_modal = true">Сгенерировать новый</button>
                                <p id="timer" class="text-xl ml-2"></p>
                            </div>
                        </div>
                        <p v-else class="underline decoration-red-500 decoration-2 underline-offset-2">Нет подключения</p>
                    </div>
                    <div @click="wiki_open = true" class="cursor-pointer group mt-2 text-center shadow dark:shadow-white hover:shadow-md dark:hover:shadow-white ml-4 mr-6 sm:mr-4 rounded-lg p-1 col-start-1 col-end-3 row-start-3 sm:row-span-2">
                        <img src="/icon/mingcute--question-line.svg" alt="How it works" style="width: 48px; height: 48px" class="mt-1 mx-auto dark:invert">
                        <p class="text-xl mt-1 mb-2.5 group-hover:underline">Как этим пользоваться?</p>
                    </div>
                </div>
            </div>
            <div v-if="confirm_modal || settings_modal" class="bg-black w-[100vw] h-full fixed top-0 opacity-70 z-40"/>
            <ConfirmModal v-if="confirm_modal" @close="confirm_modal = false" @yes="regen_token"/>
            <SettingsModal v-if="settings_modal" @close="settings_modal = false" :autostart="settings_autostart" :port="settings_port"/>
        </div>
        <div v-else>
            <button class="absolute top-10 left-12" @click="wiki_open = false">
                <img src="/icon/material-symbols--arrow-back.svg" alt="Back" style="width: 34px; height: 34px" class="dark:invert">
            </button>
            <PageHandler/>
        </div>
    </div>
</template>

<style>
@tailwind base;
@tailwind components;
@tailwind utilities;

:root {
    overflow-x: hidden;
    font-family: Inter, Avenir, Helvetica, Arial, sans-serif;
    font-size: 16px;
    line-height: 24px;
    font-weight: 400;

    background-color: rgb(244 245 246);

    font-synthesis: none;
    text-rendering: optimizeLegibility;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    -webkit-text-size-adjust: 100%;
}

:root.dark {
    background-color: rgb(35, 35, 35);
}
</style>