import Vue from 'vue'

export function gtag() {
  window.dataLayer = window.dataLayer || []
  // eslint-disable-next-line no-undef
  dataLayer.push(arguments)
}
export default {
  install() {
    Vue.prototype.$analytics = path => {
      if (process.env.VUE_APP_GOOGLE_ANALYTICS === 'true') {
        gtag('config', process.env.VUE_APP_GA_MEASUREMENT_ID, { page_path: path })
      }
    }

    if (process.env.VUE_APP_GOOGLE_ANALYTICS === 'true') {
      let googleAnalyticsPromise = new Promise(function(resolve, reject) {
        const src = 'https://www.googletagmanager.com/gtag/js?id=' + process.env.VUE_APP_GA_MEASUREMENT_ID
        if (document.querySelector('script[src="' + src + '"]')) {
          resolve()

          return
        }

        const el = document.createElement('script')

        el.type = 'text/javascript'
        el.async = true
        el.src = src

        el.addEventListener('load', resolve)
        el.addEventListener('error', reject)
        el.addEventListener('abort', reject)

        document.head.appendChild(el)
      })

      googleAnalyticsPromise.then(() => {
        gtag('js', new Date())
        gtag('config', process.env.VUE_APP_GA_MEASUREMENT_ID)
      })
    }
  },
}
