<script setup lang="ts">

import type {Component} from "vue";
import {createApp, ref} from "vue";
import type {DialogOptions} from "@/components/dialog/dialog";
import {Dialogs} from "@/services/DialogService";

const host = ref<HTMLDivElement>()
const active = ref(false)
let mountedApplication = null

Dialogs.subject.subscribe(({component, controls, props}) => {
    createDialog(component, controls, props)
})



function createDialog(component: Component, controls: DialogOptions, props: any) {
    const mergedProps = {
        onPositive: (...args) => { controls?.onPositive?.call(this, ...args); closeDialog()},
        onNegative: (...args) => { controls?.onNegative?.call(this, ...args); closeDialog()},
        onDismiss: closeDialog,
        ...props
    }

    closeDialog()
    const app = createApp(component, mergedProps)
    app.mount(host.value!!)
    mountedApplication = app
    active.value = true
}

function closeDialog() {
    if(mountedApplication != null){
        mountedApplication.unmount()
        mountedApplication = null
        active.value = false
    }
}


</script>

<template>

    <div class="host" ref="host" :class="{active}" @mousedown.self="closeDialog()">

    </div>

</template>

<style scoped lang="less">

.host {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    position: fixed;
    background: rgba(0, 0, 0, 0);
    z-index: 100;
    pointer-events: none;
    transition: 200ms opacity;
    opacity: 0;

    &.active{
        pointer-events: auto;
        background: rgba(0, 0, 0, 0.3);
        opacity: 1;
    }
}

</style>