import axios from 'axios';
import { Module, GetterTree, ActionTree, MutationTree } from 'vuex';
import {
  SET_PAGE_INFO
} from './type';

import RootState from '../../state';
import EditorState from './state';

axios.defaults.baseURL = 'http://localhost:7001';
axios.defaults.timeout = 15000;
axios.defaults.xsrfHeaderName = 'x-csrf-token';
axios.defaults.xsrfCookieName = 'csrfToken';

export default class EditorModule implements Module<EditorState, RootState> {
  state: EditorState;

  getters: GetterTree<EditorState, RootState> = {
    pageData(state) {
      return state.pageInfo.pageData;
    },
    pageId(state) {
      return state.pageInfo.id;
    }
  };

  actions: ActionTree<EditorState, RootState> = {
    async addPageDate({ commit, dispatch, state, rootState }, condition) {
      const res = await axios.post(`/editor/save`, condition);
      const { id, pageData } = res.data;
      commit(SET_PAGE_INFO, { id, pageData });
    },
    async updatePageDate({ commit, dispatch, state, rootState }, condition) {
      await axios.post(`/editor/update`, condition);
      commit(SET_PAGE_INFO, condition);
    },
    async getPageDate({ commit, dispatch, state, rootState }, condition) {
      const res = await axios.get(`/editor/get/${condition.pageId}`);
      const { id, page: pageData } = res.data;
      commit(SET_PAGE_INFO, { id, pageData: JSON.parse(pageData) });
    },
  };

  mutations: MutationTree<EditorState> = {
    [SET_PAGE_INFO](state, data) {
      state.pageInfo = data;
    },
  };

  constructor(initState: EditorState) {
    this.state = {
      pageInfo: {
        id: 0,
        pageData: {
          elements: []
        },
      },
      ...initState
    };
  }
}