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

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

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

    fastAnswers: ShmFastAnswerType[] = [];


    loadFastAnswers() {

        if (this.mode != "full") {
            return;
        }

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

    mode: ModeFWEnum = "widget";

    setMode(mode: ModeFWEnum) {
        this.mode = mode;
    }

    isFixedChannel: boolean = false;

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



    userID: string | null = null;

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

                this.userID = data ?? null;
                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" = "member";

    setChannelTab(tab: "member" | "join") {
        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;
    channelListPollingInterval: ReturnType<typeof setInterval> | null = null;

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

        const isMember = !this.channelTab || this.channelTab === "member";
        const promise = isMember
            ? rpc.channelList({}, ["shmChannelMessages"])
            : rpc.joinChannelList({}, ["shmChannelMessages"]);

        promise
            .then(({ result: data }) => {
                runInAction(() => {
                    this.channelList = data?.data ?? [];
                    if (isMember) {
                        this.channelListLastHash = data?.hash ?? null;
                    } else {
                        this.joinChannelListLastHash = data?.hash ?? null;
                    }
                });
            })
            .finally(() => {
                runInAction(() => {
                    if (isInitialLoad) {
                        this.dialogsLoading = false;
                    }
                });
            });
    }

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

        this.channelListPollingInterval = setInterval(() => {
            const isMember = !this.channelTab || this.channelTab === "member";
            const checkApi = isMember
                ? rpc.channelList
                : rpc.joinChannelList;

            checkApi({ limit: 50, offset: 0, onlyHash: true }).then(({ result: newValue }) => {
                const currentValue = isMember
                    ? this.channelListLastHash
                    : this.joinChannelListLastHash;

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

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

export default new Store();
