import axios from "axios";

export default {
  namespaced: true,
  state: {
    properties: [],
    propertiesLive: []
  },
  mutations: {
    setProperties(state, properties) {
      state.properties = properties;
    },
    removeProperties(state, id) {
      let index = 0;
      for (let i = 0; i < state.properties.length; i++) {
        if (state.properties[i].id == id) {
          index = i;
        }
      }
      state.properties.splice(index, 1);
    },
    updatePropertyPublish(state, curItem) {
      state.properties.find(item => item.id === curItem.id).isPublished = true;
    },
    updatePropertyUnpublish(state, curItem) {
      state.properties.find(item => item.id === curItem.id).isPublished = false;
    },
    setLiveProperties(state, items) {
      state.propertiesLive = items;
    }
  },
  getters: {},
  actions: {
    getAdminProperties({ commit }, userId) {
      return new Promise((resolve, reject) => {
        axios
          .get(`/api/property/GetAdminProperties/${userId}`)
          .then(result => {
            commit("setProperties", result.data);
            resolve();
          })
          .catch(() => {
            reject(console.error);
          });
      });
    },
    getProperties({ commit }, item) {
      console.log(`/api/property/GetPropertyList/${item}`);
      axios
        .get(`/api/property/GetPropertyList/${item}`) // .get(`/api/property/${item.propertyType}/${item.user}`)
        .then(result => commit("setProperties", result.data))
        .catch(console.error);
    },
    getLiveProperties({ commit }) {
      axios
        .get("/api/property/GetLivePropertyList") // .get(`/api/property/${item.propertyType}/${item.user}`)
        .then(result => commit("setLiveProperties", result.data))
        .catch(console.error);
    },
    deleteProperty({ commit }, id) {
      axios
        .delete(`/api/property/${id}`)
        .then(commit("removeProperties", id))
        .catch(console.error);
    },
    publishProperty({ commit }, item) {
      axios
        .put("/api/property/publishproperty", item)
        .then(result => commit("updatePropertyPublish", item))
        .catch(console.error);
    },
    unpublishProperty({ commit }, item) {
      axios
        .put("/api/property/unpublishproperty", item)
        .then(result => commit("updatePropertyUnpublish", item))
        .catch(console.error);
    }
  }
};
