<script setup lang="ts">
import type { FileUploadUploadEvent } from '~/node_modules/primevue/fileupload/FileUpload.d.ts'
import PF, { Grid } from 'pathfinding'
import { chunks } from '~/helpers';

const config = useRuntimeConfig()
const point_array = useState('point_array', () => [[]])
const chunk_size = useState('chunk_size', () => 8)
const threshold = useState('chunk_size', () => 20)

const paths_array = ref<{ path: string, unwalkable: boolean, x: number, y: number }[]>()
const loading = ref<boolean>(false)

const canvasElement: Ref<HTMLCanvasElement | undefined> = ref();
const context: Ref<CanvasRenderingContext2D | undefined> = ref();

const grid = ref<Grid>()
const startPoint = ref<number[]>()
const endPoint = ref<number[]>()
const startToEndPath = ref()

const selectFile = ref()
const loadingFile = ref(false)
const files = ref([])

const cw = 1920
const ch = 800

const nextFrame = () => new Promise(resolve => requestAnimationFrame(resolve));

const beforeUpload = () => {
    loading.value = true
}

const onUpload = (event: FileUploadUploadEvent) => {
    try {
        const data = JSON.parse(event.xhr.response)
        point_array.value = data.response.np_field
    } catch (error) {
        console.log(error)
    }
}
const selectFileEvent = async () => {
    loadingFile.value = true
    try {
        const res = await fetch(`${config.public.apiBase}/api/floorplan/${selectFile.value}`)
        const data = await res.json()
        point_array.value = data.np_field
    } catch (error) {
        console.log(error)
    }
    loadingFile.value = false
}
const loadFiles = async () => {
    try {
        loadingFile.value = true
        const res = await fetch(`${config.public.apiBase}/api/floorplan/`)
        const data = await res.json()
        files.value = data
    } catch (error) {
        console.log(error)
    }
    loadingFile.value = false
}

const toggleBlock = (name: string) => {
    if (openBlocks.value.includes(name)) {
        openBlocks.value.splice(openBlocks.value.indexOf(name), 1)
    } else {
        openBlocks.value.push(name)
    }
}
const isBlockOpen = (name: string) => {
    return openBlocks.value.includes(name)
}
const openBlocks = ref<string[]>([])

const fileBtnClick = async () => {
    if (isBlockOpen('upload_file')) {
        await loadFiles()
    }
    toggleBlock('upload_file')
}
onMounted(async () => {
    await loadFiles()
})
</script>
<template>
    <div class="flex flex-col gap-4">
        <Panel header="Выбор пресета">
            <div class="flex align-center gap-2">
                <Dropdown v-model="selectFile" placeholder="Выберите файл" :options="files" optionLabel="title"
                    optionValue="id" :loading="loadingFile" :disabled="!files.length || loadingFile"
                    @change="selectFileEvent" />
                <Button @click="fileBtnClick()">
                    <span style="display: contents;" v-if="isBlockOpen('upload_file')">
                        Выбрать план из загруженных
                    </span>
                    <span style="display: contents;" v-else>
                        Загрузить новый план
                    </span>
                </Button>
            </div>
        </Panel>
        <Panel header="Загрузка файла" v-if="isBlockOpen('upload_file')">
            <FileUpload mode="basic" name="demo" :url="`${config.public.apiBase}/api/floorplan/`" accept="image/*"
                :maxFileSize="10000000" @upload="onUpload" @before-upload="beforeUpload" :auto="true"
                chooseLabel="Выберите файл" :disabled="loading" />
        </Panel>

        <Panel header="Данные для работы">

        </Panel>

        <Panel :header="loading ? `Идет отрисовка` : `Обработанный план здания`">
            <div style=" max-width: 100%; overflow: auto; position: relative;">
                <FloorplanCanvas :cw="cw" :ch="ch" />
                <FloorplanSvg :cw="cw" :ch="ch" />
            </div>
        </Panel>
    </div>
</template>
