import {
    makeAutoObservable,
    runInAction,
} from 'mobx';

import { rpc } from '../api/request';
import {
    ShmChannelType,
    ShmFastAnswerType,
} from '../api/types';

class Store {
    constructor() {
        makeAutoObservable(this);
    }

    fastAnswers: ShmFastAnswerType[] = [];


    loadFastAnswers() {

        if (!this.authEnabled) {
            return;
        }

        rpc.fastAnswers().then(({ result: data }) => {
            this.fastAnswers = data ?? [];
        });
    }


    isFixedChannel: boolean = false;

    setIsFixedChannel(isFixedChannel: boolean) {
        this.isFixedChannel = isFixedChannel;
    }



    userID: string | null = null;
    authEnabled: boolean = false;

    loadUser() {
        return new Promise((resolve) => {
            rpc.profileInfo().then(({ result: data }) => {

                this.userID = data?.profileID ?? null;
                this.authEnabled = data?.authEnabled ?? false;
                resolve(true);
            });
        });
    }



    viewportWidth: number = typeof window !== 'undefined' ? window.innerWidth : 1024;

    setViewportWidth(width: number) {
        this.viewportWidth = width;
    }

    isMobile = () => {
        return this.viewportWidth < 768 || this.cap;
    }

    //Проверка на Capacitor
    cap: boolean = false;

    setCap(cap: boolean) {
        this.cap = cap;
    }



    channelTab: "member" | "join" | "closed" = "member";

    setChannelTab(tab: "member" | "join" | "closed") {
        this.channelTab = tab;
    }

    selectChannel: ShmChannelType | null = null;

    setSelectChannel(channel: ShmChannelType | null) {
        this.selectChannel = channel;
    }

    dialogsLoading = false;
    channelList: ShmChannelType[] = [];
    channelListLastHash: string | null = null;
    joinChannelListLastHash: string | null = null;
    closedChannelListLastHash: string | null = null;
    channelListPollingInterval: ReturnType<typeof setInterval> | null = null;

    private channelListApi() {
        switch (this.channelTab) {
            case "join":
                return rpc.joinChannelList;
            case "closed":
                return rpc.closedChannelList;
            case "member":
            default:
                return rpc.channelList;
        }
    }

    private getChannelListLastHash(): string | null {
        switch (this.channelTab) {
            case "join":
                return this.joinChannelListLastHash;
            case "closed":
                return this.closedChannelListLastHash;
            case "member":
            default:
                return this.channelListLastHash;
        }
    }

    private setChannelListLastHash(hash: string | null) {
        switch (this.channelTab) {
            case "join":
                this.joinChannelListLastHash = hash;
                break;
            case "closed":
                this.closedChannelListLastHash = hash;
                break;
            case "member":
            default:
                this.channelListLastHash = hash;
                break;
        }
    }

    loadChannelList() {
        const isInitialLoad = this.channelList.length === 0;
        if (isInitialLoad) {
            this.dialogsLoading = true;
        }

        this.channelListApi()({}, ["shmChannelMessages"])
            .then(({ result: data }) => {
                runInAction(() => {
                    this.channelList = data?.data ?? [];
                    this.setChannelListLastHash(data?.hash ?? null);
                });
            })
            .finally(() => {
                runInAction(() => {
                    if (isInitialLoad) {
                        this.dialogsLoading = false;
                    }
                });
            });
    }

    startChannelListPolling() {
        this.stopChannelListPolling();
        const CHECK_INTERVAL_MS = 5000;

        this.channelListPollingInterval = setInterval(() => {
            this.channelListApi()({ limit: 50, offset: 0, onlyHash: true }).then(({ result: newValue }) => {
                const currentValue = this.getChannelListLastHash();
                const nextHash = newValue?.hash ?? null;

                if (nextHash != null && nextHash !== currentValue) {
                    this.loadChannelList();
                }
            });
        }, CHECK_INTERVAL_MS);
    }

    stopChannelListPolling() {
        if (this.channelListPollingInterval) {
            clearInterval(this.channelListPollingInterval);
            this.channelListPollingInterval = null;
        }
    }
}

export default new Store();
