import Vue from "vue";
import Vuex from "vuex";
import axios from "axios";
import { account_type_text } from "@/utils/utils";

Vue.use(Vuex);

// $store.state.count
const state = {
  not_connected: false,
  connected: false,
  admin: false,
  user_info: null, //{firstname: 'toto', lastname: 'TOTO'}

  my_requests: [],
  admin_requests: [],

  my_request_dict: {},
  admin_requests_dict: {},
  admin_requests: [],

  timeline: [],
  printers: [],
  queues: [],
  users: [],

  global_error: { show: false, msg: "" }
};

const mutations = {
  set_printers(state, data) {
    // console.log(data)
    state.printers = data
  },
  display_error(state, msg) {
    state.global_error = {
      show: true,
      msg: msg
    };
    setTimeout(() => {
      state.global_error.show = false
    }, 9000)
  },
  not_connected(state) {
    state.not_connected = true;
  },
  users_list_udpate(state, users) {
    state.users = users;
    state.users.forEach(elem => {
      elem.changes = {};
    });
  },
  close_error_message(state) {
    state.global_error.show = false;
  },
  set_user_info(state, info) {
    state.user_info = info;
    if (state.user_info["access"] == 2) state.admin = true;
    state.user_info["account_type"] = account_type_text(info["access"]);
    state.connected = true;
  },
  set_my_requests(state, infos) {
    // state.my_requests = infos
    state.my_request_dict = {};
    infos.forEach(element => {
      state.my_request_dict[element.request_id] = element;
    });    
  },
  update_request(state, info) {
    state.admin_requests_dict[info.request_id] = info;
    if (info.request_id in state.my_request_dict) {
      state.my_request_dict[info.request_id] = info;
    }
  },
  set_admin_requests(state, infos) {
    // console.log(infos)
    // state.admin_requests = infos
    state.admin_requests = infos;
    state.admin_requests_dict = {};
    infos.forEach(element => {
      state.admin_requests_dict[element.request_id] = element;
    });
  },
  set_queues(state, infos) {
    let toString = function() {return this.name}
    for(let q of infos) {
      q.toString = toString
    }
    state.queues = infos;
  }
};

const actions = {
  load_printers({ commit }) {
    axios
      .get("/printers")
      .then(resp => {
        if (resp.status != 200) return;
        commit("set_printers", resp.data)
      })
      .catch(err => {
        console.log(err);
        commit("display_error", err);
      })
  },
  load_queues({ commit }) {
    axios
      .get("/queues")
      .then(resp => {
        if (resp.status != 200) return;
        commit("set_queues", resp.data);
      })
      .catch(err => {
        console.log(err);
        commit("display_error", err);
      })
  },
  load_user_infos({ commit }) {
    axios
      .get("/whoami")
      .then(resp => {
        if (resp.status != 200) return;
        commit("set_user_info", resp.data);
      })
      .catch(err => {
        console.log(err);
        commit("not_connected");
      });
  },
  update_requests({ commit, state }, filters) {
    axios
      .post("/requests/list", filters)
      .then(resp => {
        commit("set_admin_requests", resp.data);
      })
      .catch(err => {
        console.log(err);
        commit("display_error", err);
      });
  },
  reload_request({ commit, state }, id) {
    return new Promise((resolve, reject) => {
      axios
        .get(`/requests/${id}`)
        .then(resp => {
          commit("update_request", resp.data[0]);
          resolve();
        })
        .catch(err => {
          console.error(err);
          reject();
        });
    });
  },
  update_request({ commit, dispatch }, { id, changes }) {
    return new Promise((resolve, reject) => {
      axios
        .put(`/requests/${id}`, changes)
        .then(resp => {
          dispatch("reload_request", id).then(() => {
            resolve();
          });
        })
        .catch(err => {
          console.error(err);
          commit("display_error", err);
          reject(err);
        });
    });
  },
  update_my_requests({ commit, state }) {
    axios
      .get("/requests/my")
      .then(resp => {
        commit("set_my_requests", resp.data);
      })
      .catch(err => {
        console.log(err);
        commit("display_error", err);
        throw err;
      });
  },
  fetch_users({ commit }) {
    axios
      .get("/users")
      .then(resp => {
        commit("users_list_udpate", resp.data);
      })
      .catch(err => {
        commit("display_error", err);
      });
  }
};

const getters = {
  getPrintRequest: state => id => {
    return state.admin_requests_dict[id];
  }
};

export default new Vuex.Store({
  state,
  mutations,
  getters,
  actions
});
