import './public-path';
import Vue from 'vue'
import App from './App.vue'
import { routes } from './router'
import Router from 'vue-router'
import { sprintf } from 'sprintf-js'
import store from '@/store/store'
import translate from '@/plugins/translations'
import upperFirst from 'lodash/upperFirst'
import camelCase from 'lodash/camelCase'

import {
  getOption,
  setOption,
  saveOptions,
  getInfo,
  loadInfo,
  getDefaultLanguage,
  setDefaultLanguage,
  getAssetsURL,
  purgeCache,
  isRTLLanguage,
  updateConsentStatus,
  updateReviewData
} from '@/helpers/common'

Vue.use(Router)
Vue.config.productionTip = false
Vue.prototype.$i18n = translate
Vue.prototype.$globals = window.wccGlobals

const requireComponent = require.context(
	'@/components/base', true, /\.vue$/
)

requireComponent.keys().forEach(fileName => {
	const componentConfig = requireComponent(fileName)
	const componentName = upperFirst(
		camelCase(fileName.replace(/^\.\//, '').replace(/\.\w+$/, '').replace(/Index$/, ''))
	)
	Vue.component(componentName, componentConfig.default || componentConfig)
});

Vue.mixin({
  methods: {
    sprintf,
    getOption,
    setOption,
    saveOptions,
    getInfo,
    loadInfo,
    getDefaultLanguage,
    setDefaultLanguage,
    getAssetsURL,
    purgeCache,
    isRTLLanguage,
    updateConsentStatus,
    updateReviewData
  },
})

// Vue js directlive to click outside.
Vue.directive('click-outside', {
  bind: function (el, binding, vnode) {
    el.eventOnClick = function (event) {
      if (!(el == event.target || el.contains(event.target))) {
        vnode.context[binding.expression](event);
      }
    };
    document.body.addEventListener('click', el.eventOnClick)
  },
  unbind: function (el) {
    document.body.removeEventListener('click', el.eventOnClick)
  },
});

export default class wccVue {
  constructor() {
    this.Vue = Vue;
    this.Router = Router;
    this.App = App;
  }
}
window.wccVue = new wccVue();
const router = new window.wccVue.Router({
  routes: routes,
});

/**
 * 
 * @param {string} name Route name.
 * @returns object
 */
router.getRouteByName = function (name) {
  if (name) {
    return routes.find(r => {
      return name === r.name
    })
  }
  return false
}
router.redirectToDashboard = function (current) {
  if (current && current === 'customize') return;
  const route = router.getRouteByName('customize');
  router.push({ name: route.name, query: route.query });
}
router.beforeEach((to, from, next) => {
  const paths = [
    '/customize',
    '/settings'
  ];
  if (to.path && to.path === '/') {
    next({ name: 'customize' });
  } else {
    const account = getOption('account');
    if (account.connected) {
      if (!paths.some(data => data === to.path)) {
        next({ name: 'customize' });
      } else {
        next();
      }
    }
    else {
      next();
    }
  }
});

String.prototype.addQuery = function (obj) {
  return this + Object.keys(obj).reduce(function (p, e, i) {
    return p + (i == 0 ? "?" : "&") +
      (Array.isArray(obj[e]) ? obj[e].reduce(function (str, f, j) {
        return str + e + "=" + encodeURIComponent(f) + (j != obj[e].length - 1 ? "&" : "")
      }, "") : e + "=" + encodeURIComponent(obj[e]));
  }, "");
}
router.getQueryParams = function (url) {
  let queryString = url ? url.split('?')[1] : window.location.search.slice(1);
  let obj = {};

  if (queryString) {
    queryString = queryString.split('#')[0];
    let arr = queryString.split('&');

    for (let i = 0; i < arr.length; i++) {
      let a = arr[i].split('=');
      let paramNum = undefined;
      let paramName = a[0].replace(/\[\d*\]/, function (v) {
        paramNum = v.slice(1, -1);
        return '';
      });

      let paramValue = typeof (a[1]) === 'undefined' ? true : a[1];
      paramName = paramName.toLowerCase();
      paramValue = paramValue.toLowerCase();

      if (obj[paramName]) {
        if (typeof obj[paramName] === 'string') {
          obj[paramName] = [obj[paramName]];
        }
        if (typeof paramNum === 'undefined') {
          obj[paramName].push(paramValue);
        } else {
          obj[paramName][paramNum] = paramValue;
        }
      }
      else {
        obj[paramName] = paramValue;
      }
    }
  }

  return obj;
}
router.redirectToApp = function (path = 'customize') {
  const url = router.getAppRedirectURL( path );
  router.redirectToURL(url);
}
router.getAppRedirectURL = function( path = 'customize') {
  const account = getOption('account');
  if (!account.connected) return false;
  let url = window.wccGlobals.webApp.url + '/' + path;
  let query = {
    website: account.website_id,
  };
  url = url.addQuery(query);
  return url;
}
router.redirectToURL = function (url) {
  try {
    const a = document.createElement('a');
    a.target = '_blank';
    a.href = url;
    a.rel = 'noopener noreferrer'
    a.click();

  } catch (e) {
    alert('Your browser blocked the authorization window from opening. Please check your popup settings.')
  }
}
window.wccGlobals.vueApp = new window.wccVue.Vue({
  render: h => h(App),
  store,
  router: router,
}).$mount('#wcc-app')
