import { Instance, types } from 'mobx-state-tree';
import { RedmineTypes } from '../redmine-types';
import axios from 'axios';

export const IssueStore = types.frozen<RedmineTypes.ExtendedIssue>();

export type IIssueStore = Instance<typeof IssueStore>;

export const MetaInfoStore = types.model({
  title: types.string,
  url: types.maybe(types.string),
  rootIssue: types.maybe(
    types.model({
      id: 0,
      tracker: types.model({
        id: 0,
        name: '',
      }),
      subject: '',
    }),
  ),
});

export const BoardStore = types.model({
  data: types.array(IssueStore),
  metainfo: MetaInfoStore,
});

export type IBoardStore = Instance<typeof BoardStore>;

export const PageStore = types
  .model({
    loaded: false,
    type: '',
    name: '',
    data: types.maybeNull(types.array(BoardStore)),
  })
  .actions((self) => {
    return {
      setData: (data: any) => {
        self.data = data;
        self.loaded = true;
      },
    };
  })
  .views((self) => {
    return {
      get issueIds(): number[] {
        if (!self.data) return [];
        const data = self.data;
        const res = [] as number[];
        for (let i = 0; i < data.length; i++) {
          const itemData = data[i];
          for (let j = 0; j < itemData.data.length; j++) {
            const issue = itemData.data[j];
            if (res.indexOf(issue.id) < 0) {
              res.push(issue.id);
            }
          }
        }
        return res;
      },
    };
  });

export async function PageStoreLoadData(store: IPageStore): Promise<void> {
  const url = `${process.env.REACT_APP_BACKEND}simple-kanban-board/${store.type}/${store.name}/raw`;
  const resp = await axios.get(url);
  if (!resp?.data) return;

  const data = [];
  for (let i = 0; i < resp.data.length; i++) {
    const item = resp.data[i] as { data: any[]; metainfo: Record<string, any> };
    data.push({
      metainfo: item.metainfo,
      data: item.data
        ? item.data
            .map((group: { status: string; count: number; issues: any[] }) => {
              return group.issues;
            })
            .flat()
        : [],
    });
  }

  /* DEBUG: begin */
  console.debug(`Issues list board store data: ${JSON.stringify(data)}`);
  /* DEBUG: end */

  store.setData(data);
}

export type IPageStore = Instance<typeof PageStore>;
