<script lang="ts" setup>
import { BLOCKED_SITES_REPO_KEY } from "@/utils/proxy-service-keys";
import { BlockedSite } from "@/utils/types";
import { createProxyService } from '@webext-core/proxy-service';
import { v4 as uuidv4 } from "uuid"

const blockedSitesRepo = createProxyService(BLOCKED_SITES_REPO_KEY);

const props = defineProps<{}>()

const blockedSites = ref<BlockedSite[]>([]);
const inputNewSite = ref<string | null>();

const refreshBlockedSite = async () => {
  blockedSites.value = await blockedSitesRepo.getAll();
}

onBeforeMount(async () => refreshBlockedSite())

const insertBlockedSite = async () => {
  if (!inputNewSite.value) return
  if (!inputNewSite.value.trim()) return
  const generateTodoId = uuidv4()
  await blockedSitesRepo.insert({
    id: generateTodoId,
    url: inputNewSite.value,
    blocked: true
  })
  inputNewSite.value = null
  refreshBlockedSite()
}

const updateBlockedSite = async (blockedSite: BlockedSite) => {
  await blockedSitesRepo.update(toRaw(blockedSite))
  refreshBlockedSite()
}

const deleteBlockedSite = async (blockedSite: BlockedSite) => {
  await blockedSitesRepo.delete(toRaw(blockedSite))
  refreshBlockedSite()
}

</script>

<template>
    <div class="container">
        <h2>[blocked sites]</h2>
        <div class="form-input">
            <input @keydown.enter="insertBlockedSite" v-model="inputNewSite" placeholder="ba-ka.org" type="input"/>
            <button @click="insertBlockedSite">[add site]</button>
        </div>
        <br/>
        <div v-if="blockedSites.length === 0">no blocked sites :(</div>
        <ul v-else v-for="blockedSite in blockedSites">
            <li :key="blockedSite.id">
                <label>
                    <input type="checkbox" @change="updateBlockedSite(blockedSite)" v-model="blockedSite.blocked" :id="blockedSite.id"/>
                    {{ blockedSite.url }}
                    <button class="button-delete" @click="deleteBlockedSite(blockedSite)">x</button>
                </label>
            </li>
        </ul>
    </div>
</template>

<style scoped>
    .container {
        min-width: 300px;
    }

    ul {
        padding: 0;
    }

    li {
        list-style: none;
        text-align: left;
        font-size: 14pt;
    }

    li label {
        display: block;
    }

    li label:hover {
        cursor: pointer;
        border: 1px solid #ffffff;
    }

    li .button-delete {
        display: none;
        padding: 1px 4px;
        font-size: 10pt;
        float: right
    }

    li:hover .button-delete {
        display: inline-block;
    }

    .form-input input,
    .form-input button {
        width: 100%;
        padding: 2px 4px;
        margin-bottom: 5px;
    }

    .form-input input {
        font-size: 12pt;
        box-sizing: border-box;
        -webkit-box-sizing:border-box;
        -moz-box-sizing: border-box;
    }
</style>
