import { staticLinkGenerator } from '@/config/static-links'
import _ from 'lodash'

/*
 * Load Agreements
 *
 * Agreements are processed in file name order, the later replaces the old one
 */
const requireComponent = require.context('./agreements', false, /.ts$/)

let agreementProcessors: { [key: string]: AgreementsInterface } = {}

requireComponent.keys().forEach(fileName => {
  agreementProcessors[fileName.replace(/[^\w\s]/gi, '')] = requireComponent(fileName).default
})

export default function getCheckoutAgreement(state: any, getters: any, rootState: any, rootGetters: any) {
  let countryName = (rootGetters.getCountryNameById(rootGetters.getAppLocationCountry.countryId) || '').toLowerCase()
  let countryIsoCode = rootGetters.getSelectedCountry.code_iso_2

  let links: { [key: string]: string } = {
    shipping: staticLinkGenerator('SHIPPING'),
    termsOfAgreement: staticLinkGenerator('TOA', countryIsoCode),
    rentalTerms: staticLinkGenerator('RENTAL_TOA', countryIsoCode),
    rulesAndRegulations: staticLinkGenerator('RNR', countryIsoCode),
  }

  let processors: AgreementsInterface[] = []

  _(agreementProcessors)
    .keys()
    .sort()
    .reverse()
    .each(function(key: string) {
      let process: any = agreementProcessors[key]

      processors.push(new process())
    })

  let agreement: Agreement | null = null

  processors.every((process: AgreementsInterface) => {
    if (process.appArea === 'all' || rootGetters.getAppStatus(process.appArea) === true) {
      agreement = process.processAgreement(rootState, rootGetters, countryName, links)

      if (agreement !== null) {
        return false
      }
    }
    return true
  })

  return agreement !== null ? agreement!.messages : []
}

export type AppAreas = 'all' | 'eshop' | 'enrolment' | 'virel' | 'esac' | 'subscription'

export type Agreement = {
  name: AppAreas
  messages: string[]
}

export interface AgreementsInterface {
  appArea: AppAreas

  processAgreement(
    rootState: any,
    rootGetters: any,
    country: string,
    links: { [key: string]: string }
  ): Agreement | null
}
