import _ from 'lodash'
import helpers from '@/helpers'
import { CART_NAME, SELECTED_COUNTRY } from '@/store/utils/localStorageKeys'

export default {
  getCountryList: state => state.countries,
  getNationalityList: state => {
    return state.nationality
      .map(country => ({
        value: country.id,
        text: helpers.getValue(country, 'translated_name.content', country.name),
        code: country.code,
        iso: country.code_iso_2,
        call_code: country.call_code,
        currency: country.currency,
      }))
      .sort(function(a, b) {
        return a.value - b.value
      })
  },
  getCountries: state => {
    let countries = []
    state.countries.forEach(country => {
      let translatedName = helpers.getValue(country, 'translated_name.content', country.name)

      countries.push({
        value: country.id,
        text: translatedName,
        custom_text: helpers.getValue(country, 'translated_eshop_name.content', country.eshop_name || translatedName),
        code: country.code,
        iso: country.code_iso_2,
        call_code: country.call_code,
        currency: country.currency,
      })
    })
    return countries
  },
  getAllCountries: state => {
    return state.allCountries
  },
  getSelectedCountry: (state, getters) => {
    if (getters.getAppStatus('enrolment')) {
      return getters.getEnrolmentRegion
    }
    return state.selectedCountry
  },
  getSelectedCountryName: state => {
    if (state.selectedCountry !== null) {
      return (
        helpers.getValue(state.selectedCountry, 'translated_name.content') ||
        helpers.getValue(state.selectedCountry, 'eshop_name') ||
        helpers.getValue(state.selectedCountry, 'translated_name.content', state.selectedCountry.name)
      )
    }
  },
  getSelectedCountryLocation: (state, getters) => {
    let selectedCountry = getters.getSelectedCountry
    if (
      selectedCountry !== undefined &&
      selectedCountry !== null &&
      selectedCountry['entity'] != null &&
      selectedCountry['entity']['locations'] != null
    ) {
      return selectedCountry['entity']['locations'][0]
    }
  },
  getCountriesCallCode: state => {
    let callCode = []
    state.allCountries.forEach(country => {
      callCode.push({
        value: country.id,
        text: helpers.getValue(country, 'translated_name.content', country.name),
      })
    })
    return callCode
  },
  getSelectedLanguage: (state, getters, rootState, rootGetters) => {
    if (rootGetters.getAppStatus('enrolment') === true) {
      let language = rootGetters['enrolment/getEnrolmentLanguage']
      if (language !== null) {
        return { ...language, id: language.value }
      } else {
        return { id: '' }
      }
    } else {
      return state.selectedLanguage
    }
  },
  getSelectedLanguageName: state => {
    if (state.selectedLanguage !== null && state.selectedLanguage.id !== '') {
      return state.selectedLanguage.name
    }
  },
  getSelectedLanguageCode: state => {
    if (state.selectedLanguage !== null && state.selectedLanguage.id !== '') {
      return state.selectedLanguage.locale_code.substr(0, 2).toLowerCase()
    }
    return 'en'
  },
  getLanguageList: state => {
    return _.sortBy(state.languages, ['order']).map(language => ({
      value: language.id,
      text: language.name,
      key: language.key,
      locale_code: language.locale_code,
    }))
  },
  getAllLanguages: state => {
    return [...state.languagesAll]
      .sort((a, b) => a.order - b.order)
      .map(language => ({
        text: language.name,
        value: language.id,
        key: language.key,
        locale_code: language.locale_code,
      }))
  },
  getStateList: state => {
    return state.states
  },
  getStateNameById: state => stateId => {
    let res = ''
    state.states.forEach(state => {
      if (state.id === stateId) {
        res = state.name
      }
    })
    return res
  },
  getStateListByCountryId: state => countryId => {
    let collPointStates = []
    state.states.forEach(state => {
      if (countryId === state.country_id) {
        collPointStates.push({
          id: state.id,
          name: state.name,
          cities: state.cities,
        })
      }
    })
    return collPointStates
  },
  getStateListByCountryIdFormSelect: state => countryId => {
    let collPointStates = []
    state.states.forEach(state => {
      if (countryId === state.country_id) {
        collPointStates.push({
          value: state.id,
          text: state.name,
        })
      }
    })
    return collPointStates
  },
  getCountryById: state => countryId => {
    return state.countries.find(country => country.id === countryId)
  },
  getLocationByCountryId: (state, getters) => countryId => {
    let country = getters.getCountryById(countryId)
    return helpers.getValue(country, 'entity.locations.[0]')
  },
  getLocationIdByCountryId: (state, getters) => countryId => {
    let country = getters.getLocationByCountryId(countryId)
    if (country) {
      return country.id
    }
    return false
  },
  getAppLocationCountry: (state, getters) => {
    let countryId = null
    if (getters.getAppStatus('eshop') === true) {
      countryId = getters.getSelectedCountry.id
    } else if (getters.getAppStatus('enrolment') === true) {
      countryId = getters['enrolment/getEnrolCountryId']
    } else if (getters.getAppStatus('virel') === true) {
      return getters.getVirelLocationAndCountry
    } else if (getters.getAppStatus('autoship') === true && typeof getters.getAutoshipCountry === 'number') {
      countryId = getters.getAutoshipCountry
    } else if (getters.getAppStatus('thirdPartyApps') === true) {
      // Taking from localStorage directly bcz state attach with localStorage won't reactive
      if (localStorage.getItem(SELECTED_COUNTRY) !== null) {
        // Get country id from parent app where third-party app mounted
        countryId = helpers.getValue(JSON.parse(localStorage.getItem(SELECTED_COUNTRY)), 'id', false)
      } else {
        // Set default country id if expected value not present
        countryId = helpers.getValue(getters.getCountries, '[0].value', false)
      }
    } else if (getters.getAppStatus('thirdPartyAppsResumePayment') === true) {
      countryId = getters['3rdPartyPayment/getSalesCountryId']
    } else if (getters.getAppStatus('myBundle') === true) {
      countryId = getters['myBundle/getBundleCountryId']
    } else if (getters.getAppStatus('iToken') === true) {
      countryId = getters['itoken/getITokenRedemptionCountryId']
    } else {
      countryId = getters.getMemberCountryId
    }
    let locationId = getters.getLocationIdByCountryId(countryId)
    return {
      locationId: locationId,
      countryId: countryId,
    }
  },
  getCountryNameById: state => countryId => {
    let res = null
    state.countries.forEach(country => {
      if (country.id === countryId) {
        res = country.name
      }
    })
    return res
  },
  getShippingData: state => {
    return state.shippingData
  },
  getShippingCountries: state => {
    return state.shippingCountries
  },
  getStockistStatesByCountry: state => countryId => {
    return Array.isArray(state.stockistStateAndCities[countryId])
      ? state.stockistStateAndCities[countryId]
          .filter(st => typeof st.location_id !== 'undefined' && st.location_id !== null)
          .map(st => {
            return {
              id: st.state_id !== null && st.state_id !== undefined ? st.state_id : st.id,
              location_id: st.location_id,
              name: (st.state !== null && st.state !== undefined ? st.state.name + ' - ' : '') + st.area,
            }
          })
      : []
  },
  getStockistCitiesByState: state => stateId => {
    return _.chain(state.stockistStateAndCities)
      .values()
      .first()
      .find(st => {
        return st.id === stateId
      })
      .get('cities')
      .values()
      .value()
  },
  getEnrolmentRegion: (state, rootGetters) => {
    return state.countries.find(x => x.id === rootGetters['enrolment/getEnrolCountryId'])
  },
  getLocationTypeList: state => {
    return state.locationTypeList
  },
  crossCountryDeliveryCountryIDs: state => {
    let ids = []
    if (typeof state.countryRelation.data.cross_country !== 'undefined') {
      if (state.countryRelation.data.cross_country.length > 0) {
        state.countryRelation.data.cross_country.forEach(x => {
          ids.push(x.id)
        })
      }
    }
    return ids
  },
  getCountryRelation: state => type => {
    return state.countryRelation.data[type] !== undefined ? state.countryRelation.data[type] : []
  },
  getCountryRelationOptions: state => type => {
    return (
      state.countryRelation.data[type] &&
      state.countryRelation.data[type].map(item => {
        return {
          text: item.name,
          value: item.id,
        }
      })
    )
  },
  getAutoshipCountry: state => state.autoshipCountry,
  getCartNameByAppStatus() {
    return localStorage.getItem(CART_NAME)
  },
  crossCountryRecipientCountryIDs: state => {
    let ids = []
    if (typeof state.countryRelation.data.recipient_cross_country !== 'undefined') {
      if (state.countryRelation.data.recipient_cross_country.length > 0) {
        state.countryRelation.data.recipient_cross_country.forEach(x => {
          ids.push(x.id)
        })
      }
    }
    return ids
  },
  getCurrentIPCountry: state => {
    if (state.currentIp) {
      return state.ipCountry[state.currentIp] || null
    } else {
      return state.ipCountry
    }
  },
  getDefaultPreferredGeoLanguage: (state, getters) => {
    if (state.languages) {
      let currentIpCountryCode = helpers.getValue(getters.getCurrentIPCountry, 'countryCode', null)
      if (currentIpCountryCode) {
        let langOrder = ['en', currentIpCountryCode.toLowerCase()]

        let sortedLang = [...state.languagesAll]
          .sort((item1, item2) => {
            let index1 = langOrder.indexOf(item1.key.toLowerCase())
            let index2 = langOrder.indexOf(item2.key.toLowerCase())
            if (index1 > -1 && index2 > -1) {
              return index1 - index2
            } else {
              return langOrder.length + 1
            }
          })
          .reverse()

        return sortedLang[0]
      } else {
        return [...state.languagesAll].find(lang => lang.key.toLowerCase() === 'en') || null
      }
    }
    return null
  },
  getDefaultPreferredGeoCountry: (state, getters) => {
    if (state.countries) {
      let currentIpCountryCode = helpers.getValue(getters.getCurrentIPCountry, 'countryCode', null)
      let currentIpCountryNeighbours = helpers.getValue(getters.getCurrentIPCountry, 'neighbours', [])
      if (currentIpCountryCode) {
        let neighbours = [...currentIpCountryNeighbours].map(code => code.toLowerCase())
        let countryOrder = [...neighbours, currentIpCountryCode.toLowerCase()]
        // if no neighbours found and country not found then we default to us
        if (countryOrder['us'] === undefined) {
          countryOrder.unshift('us')
        }
        let iso2 = [...state.countries].map(country => country.code_iso_2.toLowerCase())
        let sortedCountry = [...state.countries]
          .sort((item1, item2) => {
            let index1 = countryOrder.indexOf(item1.code_iso_2.toLowerCase())
            let index2 = countryOrder.indexOf(item2.code_iso_2.toLowerCase())
            return index1 - index2
          })
          .reverse()

        return sortedCountry[0]
      } else {
        return [...state.countries].find(country => country.code_iso_2.toLowerCase() === 'my') || null
      }
    }
    return null
  },
}
