
/** Dependencies */
import Vue from 'vue'
import store from './vuex/store';

window.route = require('./general/functions/router');

/** Guards */
import guards from './general/mixins/guards';

/** Validation **/
import vuelidate from 'vuelidate';

/** Input Mask **/
import VueTheMask from 'vue-the-mask';

/** Vue Filter **/
import filters from './general/filters';

/** Mixins */
import request from './general/mixins/request';
import crudHandler from './general/mixins/crudHandler';

/** Directives */
import closable from './general/directives/closable';

import { debounce } from 'vue-debounce'

import Avatar from 'vue-avatar';

import Vapor from 'laravel-vapor';
// Vapor.withBaseAssetUrl(import.meta.env.VITE_VAPOR_ASSET_URL);
window.Vapor = Vapor;

import Echo from 'laravel-echo';
import Pusher from 'pusher-js';

window.Pusher = Pusher;

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: process.env.MIX_PUSHER_APP_KEY,
    cluster: process.env.MIX_PUSHER_APP_CLUSTER,
    forceTLS: true
});


/** Application Injections */
Vue.use(vuelidate);
Vue.use(VueTheMask);
Vue.use(filters);

Vue.directive('closable', closable);
Vue.directive('tooltip', function(el, binding){
    $(el).tooltip({
        title: binding.value,
        placement: binding.arg,
        trigger: 'hover'
    })
})
Vue.mixin({
    methods: {
        route: route,
        asset: window.Vapor.asset
    },
    mixins: [request, crudHandler]
});

/** Components Registrations */
Vue.component(Avatar);

const files = require.context('./', true, /\.vue$/i);
files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key).default));

const app = new Vue({
    el: '#app',
    store,
    data(){
      return {
          captchaId: '',
          reCaptchaToken: null
      }
    },
    created(){
        this.init();
        this.routesGuard();
        if (!this.$store.getters.isAdmin && !('company_marking' in this.$store.getters.getDecodedAccessToken.user) && this.isProtectedRoute() && !this.isWithTokenRoute()) {
            this.$store.dispatch('crudRequest', {endpoint: this.route('api.account.authentication.refresh'), method: 'get'}).then(response => {
                let success = response.ok;
                response.json().then(response => {

                    if(!success){return;}

                    this.$store.dispatch('userAuthentication', {access_token: response.payload.refresh_token, redirect_url: window.location.href});

                });
            })

        }
    },
    methods: {
        route: route,
        init() {
            if (!document.getElementById('gRecaptchaScript')) {

                window.gRecaptchaOnLoadCallbacks = [this.render];
                window.gRecaptchaOnLoad = function () {
                    for (let i = 0; i < window.gRecaptchaOnLoadCallbacks.length; i++) {
                        window.gRecaptchaOnLoadCallbacks[i]();
                    }
                    delete window.gRecaptchaOnLoadCallbacks;
                    delete window.gRecaptchaOnLoad;
                };

                let recaptchaScript = document.createElement('script');
                recaptchaScript.setAttribute('src', 'https://www.google.com/recaptcha/api.js?render=explicit&onload=gRecaptchaOnLoad');
                recaptchaScript.setAttribute('id', 'gRecaptchaScript');
                recaptchaScript.async = true;
                recaptchaScript.defer = true;
                document.head.appendChild(recaptchaScript);

            } else if (!window.grecaptcha || !window.grecaptcha.render) {
                window.gRecaptchaOnLoadCallbacks.push(this.render);
            } else {
                this.render();
            }
        },
        render() {
            this.captchaId = window.grecaptcha.render('grecaptcha_container', {
                sitekey: '6Lft5mkhAAAAAAFgQ0gWlwte1h-o6UPRpMNHP1xz',
                badge: '',
                size: 'invisible',
                'expired-callback': this.execute
            });
            this.execute();
        },
        execute: debounce(function() {
            this.updateCaptchaToken();
        }, 3000),
        updateCaptchaToken() {
            if(this.$store.getters.getReCaptcha === this.reCaptchaToken){
                window.grecaptcha.execute(this.captchaId).then((token) => {
                    this.reCaptchaToken = token;
                    this.$store.dispatch('reCaptcha', {token: token});
                });
            }

        }
    },
    mixins: [guards]
});
