/* eslint-disable import/prefer-default-export */
import _ from 'lodash'
import OurVue from 'vue'
// import VueRouter from 'vue-router'
import apolloProvider from './plugins/vue-apollo'
import * as CartModule from './store/modules/cart'
import * as SalePageModule from './store/modules/sale-page'
import './plugins/lodash'
import './plugins/dayjs'
import './plugins/vue-clipboard2'
import './plugins/svg-components'

export function install (Vue, args = {}) {
  if (install.installed) return
  install.installed = true

  if (OurVue !== Vue) {
    console.error('Multiple instances of Vue detected')
  }

  // const router = args.router || {
  //   publicPath: '/',
  //   routes: {}
  // }
  const components = args.components || {}
  const directives = args.directives || {}
  const filters = args.filters || {}

  _.forEach(filters, (value, key) => {
    const filter = filters[key]
    Vue.filter(key, filter)
  })

  _.forEach(directives, (value, key) => {
    const directive = directives[key]
    Vue.directive(key, directive)
  });

  (function registerComponents (_components) {
    if (_components) {
      _.forEach(_components, (value, key) => {
        const component = _components[key]
        if (component && !registerComponents(component.$_shipnity_subcomponents)) {
          Vue.component(key, component)
        }
      })
      return true
    }
    return false
  }(components))

  if (Vue.$_shipnity_installed) return
  Vue.$_shipnity_installed = true
  Vue.mixin({
    beforeCreate () {
      const options = this.$options
      if (options.shipnity) {
        options.shipnity.init(this, this.$ssrContext)
        this.$shipnity = Vue.observable(options.shipnity.framework)
      } else {
        this.$shipnity = (options.parent && options.parent.$shipnity) || this
      }

      if (this.$store && !!options.store) {
        this.$store.registerModule('salePage', SalePageModule, {
          preserveState: Boolean(this.$store.state.salePage)
        })
        this.$store.registerModule('cart', CartModule, {
          preserveState: Boolean(this.$store.state.cart)
        })
      }
    },
    beforeMount () {
      if (this.$options.shipnity && this.$el && this.$el.hasAttribute('data-server-rendered')) {
        this.$shipnity.isHydrating = true
        this.$shipnity.breakpoint.update(true)
      }
    },
    mounted () {
      if (this.$options.shipnity && this.$shipnity.isHydrating) {
        this.$shipnity.isHydrating = false
        this.$shipnity.breakpoint.update()
      }
    },
    apolloProvider
    // router: new VueRouter({
    //   mode: 'history',
    //   routes
    // })
  })
}
