import { User } from "@/Request";

export default {
  namespaced: true,
  state: {
    account_detail: "",
    loading: false,
    error: ""
  },
  getters: {
    loading: state => state.loading,
    accountDetail: state => state.account_detail
  },
  actions: {
    accountLogin({ commit }, payload) {
      return new Promise((resolve, reject) => {
        let { username, password } = payload;
        commit("USER_INIT");
        User.accountLogin(username, password)
          .then(response => {
            commit("USER_LOGIN_SUCCESS");
            resolve(response);
          })
          .catch(error => {
            commit("USER_ERROR", error);
            reject(error);
          });
      });
    },
    getAccountDetail({ commit }) {
      return new Promise((resolve, reject) => {
        commit("USER_INIT");
        User.getAccountDetail()
          .then(response => {
            commit("GET_USER_DETAIL_SUCCESS", response);
            resolve(response);
          })
          .catch(error => {
            commit("USER_ERROR", error);
            reject(error);
          });
      });
    },
    accountLogout({ commit }) {
      return new Promise((resolve, reject) => {
        commit("USER_INIT");
        User.accountLogout()
          .then(response => {
            commit("USER_LOGOUT_SUCCESS");
            resolve(response);
          })
          .catch(error => {
            commit("USER_ERROR", error);
            reject(error);
          });
      });
    },
    accountUpdate({ commit }, payload) {
      return new Promise((resolve, reject) => {
        let {
          first_name,
          last_name,
          birth,
          phone_number,
          email,
          username
        } = payload;
        commit("USER_INIT");
        User.accountUpdate(
          first_name,
          last_name,
          birth,
          phone_number,
          email,
          username
        )
          .then(response => {
            commit("USER_UPDATE_SUCCESS", response);
            resolve(response);
          })
          .catch(error => {
            commit("USER_ERROR", error);
            reject(error);
          });
      });
    }
  },
  mutations: {
    USER_INIT: state => {
      state.loading = true;
    },
    USER_LOGIN_SUCCESS: state => {
      state.loading = false;
    },
    USER_LOGOUT_SUCCESS: state => {
      state.loading = false;
      state.account_detail = "";
    },
    GET_USER_DETAIL_SUCCESS: (state, response) => {
      state.account_detail = response;
      state.loading = false;
    },
    USER_UPDATE_SUCCESS: (state, response) => {
      state.account_detail = response;
      state.loading = false;
    },
    USER_ERROR: (state, error) => {
      state.error = error;
      state.loading = false;
    }
  }
};
