import axios from 'axios';
import { Instance, types } from 'mobx-state-tree';

type _WidgetParams = {
  collapsed?: boolean;
} & Record<string, any>;

export const WidgetParams = types.frozen<_WidgetParams>();

type _DataLoaderParams = Record<string, any> | null;

export const DataLoaderParams = types.frozen<_DataLoaderParams>();

export const Widget = types.model({
  type: types.string,
  id: types.string,
  title: types.string,
  widgetParams: types.maybe(WidgetParams),
  dataLoaderParams: types.maybe(DataLoaderParams),
});

export const Data = types.model({
  widgets: types.array(Widget),
  title: types.maybe(types.string),
});

export const Dashboard = types
  .model({
    loaded: types.boolean,
    id: types.string,
    data: types.maybe(Data),
  })
  .actions((self) => {
    return {
      setData: (data: any) => {
        self.data = data;
        self.loaded = true;
      },
    };
  });

export type IDashboard = Instance<typeof Dashboard>;

export async function DashboardLoadData(store: IDashboard): Promise<void> {
  const url = `${process.env.REACT_APP_BACKEND}api/dashboard/${store.id}`;
  const resp = await axios.get(url);
  if (!resp.data) return;
  store.setData(resp.data);
}
