import Vue from 'vue';
import App from './App.vue';
import './registerServiceWorker';
import './quasar';
import { i18n } from '@/plugins/i18n';
import map from 'lodash/map';
// @ts-ignore // FIXME Нет поддержки *.ts, добавить, когда появится
import VueFriendlyIframe from 'vue-friendly-iframe';
// @ts-ignore
import eventBus from '@utils/eventBus';
import initAppConfig from '@utils/app-config';
import VueCurrencyInput from 'vue-currency-input';
import RouterHistory from './plugins/router-history';
import { addAuthIntercepter } from '@utils/api/intercepters/request/authIntercepter';
import { AccessController } from '@utils/base/AccessController';
import GlobalComponentImporter from '@plugins/GlobalComponentImporter';
import { addTenantInterceptor } from '@utils/api/intercepters/request/tenantInterceptor';
import { saveUnauthorizedPath } from '@utils/unauthorized-path';

function init(): Promise<any> {
  return new Promise((resolve, reject) => {
    try {
      initAppConfig().then(async (response) => {
        Vue.prototype.$appConfig = response;
        const { router } = await import('./router');
        await import('@components/_globals');
        const { default: filters } = await import('@utils/filters');
        try {
          import('@state/store').then((store) => {
            Vue.prototype.$AC = new AccessController({}); // По хорошему, данные по пользователю должны быть уже на этом этапе

            Vue.use(VueFriendlyIframe);

            Vue.use(VueCurrencyInput);

            Vue.use(eventBus);

            Vue.use(RouterHistory, { router });

            Vue.use(GlobalComponentImporter);

            map(filters, (v, k) => Vue.filter(k, v));

            return resolve({
              router,
              store: store.default,
            });
          });
        } catch (e) {
          return reject(e);
        }
      });
    } catch (e) {
      return reject(e);
    }
  });
}

init().then(({ router, store }) => {
  Vue.config.productionTip = false;
  saveUnauthorizedPath(router, store);
  console.log(process.env);
  console.log(Vue.prototype.$appConfig);
  new Vue({
    router,
    store,
    i18n,
    render: (h) => h(App),
  }).$mount('#app');
  addTenantInterceptor(store);
  addAuthIntercepter();
});
