import * as actions from './actions'
import getters from './getters'
import mutations from './mutations'
import {
  ESHOP_CART_SELECTED_DUMMY_IDS,
  ESHOP_CART_SELECTED_INST_ADDRESS_DUMMY_IDS,
  ESHOP_CART_IS_ORDERING_FOR_DOWNLINE,
  ESHOP_CART_ORDERING_FOR,
  CART_NAME,
} from '../../../utils/localStorageKeys'
import _ from 'lodash'

let cartName = localStorage.getItem(CART_NAME)

export const state = {
  products: [],
  totalQuantity: 0,
  totalCv: {},
  allTotalPrices: {
    gmp_price_gst: 0,
    nmp_price: 0,
    rp_price: 0,
    rp_price_gst: 0,
  },
  loaded: false,
  selectedDummies: processLocalStorageDummies(ESHOP_CART_SELECTED_DUMMY_IDS, [
    {
      sizes: [],
      evoucher: [],
      name: cartName,
    },
  ]),
  selectedDummiesInstDetails: processLocalStorageDummies(ESHOP_CART_SELECTED_INST_ADDRESS_DUMMY_IDS, [
    {
      inst_details: [],
      name: cartName,
    },
  ]),
  promotions: [],
  total_admin_fee: 0,
  total_admin_fee_formatted: 0,
  total_delivery_fee: 0,
  total_delivery_fee_formatted: 0,
  total_npm: 0,
  total_npm_formatted: 0,
  total_price: 0,
  total_price_formatted: 0,
  total_price_rounding_adjustment: 0,
  total_price_rounding_adjustment_formatted: 0,
  total_tax: 0,
  total_tax_formatted: 0,
  checkout: {
    status: 0,
    messages: {
      default: '',
    },
    errors: {},
  },
  checkoutErrors: [],
  isOrderingForDownLine: JSON.parse(localStorage.getItem(ESHOP_CART_IS_ORDERING_FOR_DOWNLINE)) || false,
  orderingFor: JSON.parse(localStorage.getItem(ESHOP_CART_ORDERING_FOR)) || null,
  showProductDetailModal: false,
  has_epp: true,
  has_rental: false,
  has_ha: false,
  need_address_selection: false,
  need_size_selection: false,
  preserverCartItem: false,
  cartPayCycle: '',
  cartCampaignDetails: null,
}

/**
 * Process localStorage item for dummies if array return by cartName else return object
 * @param localStorageKey
 * @param defaultData
 * @returns {any}
 */
function processLocalStorageDummies(localStorageKey, defaultData) {
  let data = JSON.parse(localStorage.getItem(localStorageKey))
  if (!data) {
    data = defaultData[0]
  }

  if (Array.isArray(data)) {
    let currentCart = _.find(data, ['name', cartName])
    if (!currentCart) {
      // If not exist find return default
      return defaultData[0]
    } else {
      // If exist return currentCart
      data = currentCart
    }
  }
  return data
}

export default {
  state,
  actions,
  mutations,
  getters,
}
