import { runInAction } from "mobx";
import { getMillis } from "taehui-ts/date";

import { GetNoteAPI, NoteAPINote } from "src/wwwAPI";
import { wwwAXIOS } from "src/Www";

export default function setNoteStore() {
  let lastMillis = getMillis();
  let lastWant = "";
  let lastSrc = 0;

  return {
    totalCount: 0,
    highestCount: 0,
    wantAvatar: "",
    notes: [] as NoteAPINote[],
    fit: 0,
    src: 0,
    input: "",
    lastPage: 1,
    pageUnit: 10,
    viewUnit: 20,
    isLoading: false,

    setFit(fit: number) {
      this.fit = fit;
    },

    setSrc(src: number) {
      this.src = src;
    },

    setInput(input: string) {
      this.input = input;
    },

    async getNote(want: string, page: number, setPage: (page: number) => void) {
      this.wantAvatar = this.src === 1 ? want : "";
      if ((want !== lastWant || this.src !== lastSrc) && page > 1) {
        setPage(1);
      } else {
        const millis = getMillis();
        lastMillis = millis;
        this.isLoading = true;
        const { status, data } = await wwwAXIOS.get<GetNoteAPI>("/note", {
          params: {
            fit: this.fit,
            src: this.src,
            want,
            page,
            viewUnit: this.viewUnit,
          },
        });
        if (millis >= lastMillis) {
          if (status === 200) {
            runInAction(() => {
              this.totalCount = data.totalCount;
              this.highestCount = data.highestCount;
              this.lastPage = Math.max(
                1,
                Math.ceil(data.noteCount / this.viewUnit),
              );
              this.notes = data.notes;
              this.isLoading = false;
            });
          }
        }
      }
      lastWant = want;
      lastSrc = this.src;
    },
  };
}
