// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './app/App'
import router from './router'
import store from './store'
import { BootstrapVue, IconsPlugin } from 'bootstrap-vue'
import { sync } from 'vuex-router-sync'
// Languages supports for eshop
import vuexI18n from 'vuex-i18n'
// iBS Plugins
import ibsTemplate from './plugins/template'
import './config/menu'
import TemplateConfig from './config/template'
// Country Flags
import FlagIcon from 'vue-flag-icon'
import vSelect from 'vue-select'
// Icon Component
import Icon from 'vue-awesome/components/Icon'
import VeeValidate, { Validator } from 'vee-validate'
import { customErrorValidation } from '@/config/custom-error-validation'
import AutoComplete from 'v-autocomplete'
// Slider Componet
import bFormSlider from 'vue-bootstrap-slider'
// Security Config
import SecurityConfig from './config/security'
import Vuebar from 'vuebar'
import Helpers from '@/plugins/helpers'
import VueAffix from 'vue-affix'
// ScrollTo
import VueScrollTo from 'vue-scrollto'
// Constant
import constants from './config/const'
// App Settings
import app_settings from './config/app-settings'
// moment
import moment from 'vue-moment'
// SweetAlert
import VueSweetalert2 from 'vue-sweetalert2'
import VueProgressBar from 'vue-progressbar'
import Raven from 'raven-js'
import RavenVue from 'raven-js/plugins/vue'
import { LOGGED_IN_USER_NAME, LOGGED_IN_USER_IBO } from '@/store/utils/localStorageKeys'
import { version } from '../package'
import '@/config/global-components'
import '@/config/mobile-page'
// googleAnalytics
import googleAnalytic from '@/plugins/google-analytics/index'
var path = require('path')
//Vue-Echo
import VueEcho from 'vue-echo'
import VueTouch from 'vue-touch'
import './registerServiceWorker'
// translation pack
import langEn from '@/resources/locales/ibs/locale-en.json'
import langId from '@/resources/locales/ibs/locale-id.json'
import langKm from '@/resources/locales/ibs/locale-km.json'
import langMy from '@/resources/locales/ibs/locale-my.json'
import langTh from '@/resources/locales/ibs/locale-th.json'
import langTw from '@/resources/locales/ibs/locale-tw.json'
import langZh from '@/resources/locales/ibs/locale-zh.json'
import langHk from '@/resources/locales/ibs/locale-hk.json'

Vue.config.productionTip = false
const isEvo = app_settings.evo.enable

// Sync Routes to store
sync(store, router)

// Initialize store
Vue.use(vuexI18n.plugin, store)

// Initialize Boostrap
Vue.use(BootstrapVue)
Vue.use(IconsPlugin)
Vue.use(Vuebar)
// Boostrap custom components
Vue.use(bFormSlider)

VueTouch.config.swipe = {
  direction: 'horizontal',
}

Vue.use(VueTouch)

// Initialize Template Plugin
Vue.use(ibsTemplate, TemplateConfig)
Vue.use(FlagIcon)

Vue.use(Helpers)
Vue.component('v-select', vSelect)
// https://justineo.github.io/vue-awesome/demo/
Vue.component('icon', Icon)
Vue.use(VueProgressBar, {
  color: '#f287b7',
  failedColor: 'red',
  height: '2px',
  location: 'top',
  inverse: false,
  transition: {
    speed: '0.5s',
    opacity: '0.6s',
    termination: 15000,
  },
})
//initiate googleAnalytics
Vue.use(googleAnalytic)
// Validator
Validator.localize('en', customErrorValidation)
const config = {
  enableAutoClasses: true,
  inject: false,
  classNames: {
    touched: 'touched', // the control has been blurred
    untouched: 'untouched', // the control hasn't been blurred
    valid: 'valid', // model is valid
    invalid: 'invalid', // model is invalid
    pristine: 'pristine', // control has not been interacted with
    dirty: 'dirty', // control has been interacted with
  },
}
Vue.use(VeeValidate, config)
// Autocomplete
Vue.use(AutoComplete)

// Vue Affix
Vue.use(VueAffix)

// Vue ScrollTo
Vue.use(VueScrollTo, {
  container: 'body',
  duration: 1000,
  easing: 'linear',
  offset: -10,
  cancelable: true,
  onStart: false,
  onDone: false,
  onCancel: false,
  x: false,
  y: true,
})

// Moment
Vue.use(moment)

// SweetAlert
Vue.use(VueSweetalert2)

// Constant
constants.install = function() {
  Object.defineProperty(Vue.prototype, '$const', {
    get() {
      return constants
    },
  })
}
Vue.use(constants)

// App Settings
Vue.use({
  install: function() {
    Object.defineProperty(Vue.prototype, '$appSettings', {
      get() {
        return app_settings
      },
    })
  },
})

//  Define default translations for eshop
let evoLangEn, evoLangId, evoLangHk, evoLangKm, evoLangMy, evoLangTh, evoLangTw, evoLangZh
let selectedLanguage = ((JSON.parse(localStorage.getItem('SELECTED_LANGUAGE')) || {}).key || 'en').toLowerCase()
const getTranslationPack = function(ibsPack = {}, evoPack = {}) {
  return isEvo ? { ...ibsPack, ...evoPack } : ibsPack
}

if (isEvo) {
  evoLangEn = require('@/resources/locales/evo/locale-en.json')
  evoLangId = require('@/resources/locales/evo/locale-id.json')
  evoLangKm = require('@/resources/locales/evo/locale-km.json')
  evoLangMy = require('@/resources/locales/evo/locale-my.json')
  evoLangTh = require('@/resources/locales/evo/locale-th.json')
  evoLangTw = require('@/resources/locales/evo/locale-tw.json')
  evoLangZh = require('@/resources/locales/evo/locale-zh.json')
  evoLangHk = require('@/resources/locales/evo/locale-hk.json')
}

Vue.i18n.add('en', getTranslationPack(langEn, evoLangEn))
Vue.i18n.add('id', getTranslationPack(langId, evoLangId))
Vue.i18n.add('kh', getTranslationPack(langKm, evoLangKm))
Vue.i18n.add('my', getTranslationPack(langMy, evoLangMy))
Vue.i18n.add('th', getTranslationPack(langTh, evoLangTh))
Vue.i18n.add('tw', getTranslationPack(langTw, evoLangTw))
Vue.i18n.add('ch', getTranslationPack(langZh, evoLangZh))
Vue.i18n.add('hk', getTranslationPack(langHk, evoLangHk))

// set the start locale to use
Vue.i18n.set(selectedLanguage)
Vue.i18n.fallback('en')

// Add router to security config
SecurityConfig.router = router

Vue.use(SecurityConfig)

// Keycodes
Vue.config.keyCodes = {
  'form-submit': 13,
}

// Global Events
const EventBus = new Vue()

Object.defineProperties(Vue.prototype, {
  $bus: {
    get: function() {
      return EventBus
    },
  },
})

// App Settings
Vue.use({
  install: function() {
    Object.defineProperty(Vue.prototype, '$appStore', {
      get() {
        return store
      },
    })
  },
})

if (process.env.VUE_APP_LOG_SENTRY === 'true') {
  // var Raven = require('raven-js')
  // GLOBAL.RELEASE_VERSION
  Raven.config(process.env.VUE_APP_SENTRY_DSN, {
    release: version,
    dataCallback: function(data) {
      var stacktrace = data.exception && data.exception.values[0].stacktrace

      if (stacktrace && stacktrace.frames) {
        stacktrace.frames.forEach(function(frame) {
          if (frame.filename.startsWith('/') || frame.filename.startsWith('src')) {
            frame.filename = 'webpack-internal:///' + path.basename(frame.filename)
          }
        })
      }

      return data
    },
  })
    .addPlugin(RavenVue, Vue)
    .install()
  Raven.setUserContext({
    name: localStorage.getItem(LOGGED_IN_USER_NAME),
    id: localStorage.getItem(LOGGED_IN_USER_IBO),
  })
}

if (process.env.VUE_APP_WEBSOCKET === 'true') {
  window.io = require('socket.io-client')
  if (process.env.VUE_APP_ECHO_URL && process.env.VUE_APP_ECHO_URL !== '') {
    Vue.use(VueEcho, {
      broadcaster: 'socket.io',
      host: process.env.VUE_APP_ECHO_URL,
      auth: {
        headers: {
          Authorization: 'Bearer ' + localStorage.getItem('API_TOKEN'),
        },
      },
    })
  } else {
    /* eslint no-console: ["error", { allow: ["warn", "error"] }] */
    console.error('_ENV_ECHO_URL_NOT_SPECIFIED')
  }
}

/* eslint-disable no-new */
export default new Vue({
  el: '#app',
  store,
  router,
  render: h => h(App),
}).$mount('#app')
