<template>
    <template v-if="waitIncoming">
        <i class="ph-circle-notch ph-bold ph-lg fa-pulse ph-fw ph-lg"></i>
    </template>
    <template v-else>
        <button
            class="_textButton"
            :disabled="waitIncoming"
            @click.stop="accept(user)"
        >
            <i class="ph-check ph-bold ph-lg"></i>
            <span class="follow-approve-label">
                {{ i18n.ts.accept }}
            </span>
        </button>
        |
        <button
            class="_textButton"
            :disabled="waitIncoming"
            @click.stop="reject(user)"
        >
            <i class="ph-x ph-bold ph-lg"></i>
            <span class="follow-approve-label">
                {{ i18n.ts.reject }}
            </span>
        </button>
    </template>
</template>

<script lang="ts" setup>
import { onBeforeUnmount, onMounted, ref } from "vue";
import type * as Misskey from "calckey-js";
import * as os from "@/os";
import { i18n } from "@/i18n";
import { useRouter } from "@/router";
import { stream } from "@/stream";
import { globalEvents } from "@/events";
import { packed } from "magnetar-common";

const router = useRouter();

const emit = defineEmits(["refresh"]);
const props = defineProps<{
    user: packed.PackUserBase | Misskey.entities.User;
}>();

let state = ref(i18n.ts.processing);
const connection = stream.useChannel("main");

let waitIncoming = ref(false);

function accept(user: packed.PackUserBase | Misskey.entities.User) {
    waitIncoming.value = true;
    os.api("following/requests/accept", { userId: user.id }).then(() => {
        globalEvents.emit("followeeProcessed", user);
    });
}

function reject(user: packed.PackUserBase | Misskey.entities.User) {
    waitIncoming.value = true;
    os.api("following/requests/reject", { userId: user.id }).then(() => {
        globalEvents.emit("followeeProcessed", user);
    });
}

function onFolloweeChange(user: Misskey.entities.User) {
    if (user.id === props.user.id) {
        emit("refresh");
    }
}

onMounted(() => {
    globalEvents.on("followeeProcessed", onFolloweeChange, this);
});

onBeforeUnmount(() => {
    globalEvents.off("followeeProcessed", onFolloweeChange, this);
});
</script>

<style lang="scss" scoped>
.follow-approve-label {
    padding-left: 0.25em;
}
</style>
