import axios from "axios";
import log from "../../../assets/Log";
import { result } from "lodash";

export default {
  namespaced: true,
  state: {
    bidItem: {},
    bidItems: []
  },
  mutations: {
    setBid(state, bid) {
      state.bidItem = bid;
    },
    setBids(state, bid) {
      state.bidItems = bid;
    },
    addToBids(state, bid) {
      state.bidItems.push(bid);
    },
    updateBidList(state, bid) {
      state.bidItems.find(item => item.id === bid.id).status = bid.status;
    }
  },
  getters: {},
  actions: {
    getTemplate({ commit }) {
      axios.get("/api/bid/GetNewBidTemplate").then(result => commit("setBid", result.data))
      .catch(ex => console.log(ex.response));
    },
    getBid({ commit }, id) {
      axios
        .get(`/api/bid/${id}`)
        .then(result => commit("addToBids", result.data))
        .catch(ex => console.log(ex.response));
    },
    getBids({ commit }, username) {
      axios
        .get(`/api/bid/GetBids/${username}`)
        .then(result => commit("setBids", result.data))
        .catch(ex => console.log(ex.response));
    },
    saveBid({ commit }, item) {
      if (log.isLoggedIn()) {
        item.userId = log.getUser().id;
      }
      console.log(JSON.stringify(item));
      axios
        .post("/api/bid", item)
        .then(result => commit("setBid", result.data))
        .catch(ex => console.log(ex.response));
    },
    updateBid({ commit }, item) {
      axios
        .put("/api/bid", item)
        .then(result => commit("setBid", item))
        .catch(ex => console.log(ex.response));
    },
    acceptBid({ commit }, id) {
      axios
        .put(`/api/bid/AcceptBid/${id}`)
        .then(result => commit("updateBidList", result.data))
        .catch(ex => console.log(ex.response));
    },
    declineBid({ commit }, item) {
      axios
        .put("/api/bid/DeclineBid", item)
        .then(result => commit("updateBidList", result.data))
        .catch(ex => console.log(ex.response));
    }
  }
};
