import { createApp } from 'vue';
import axios from 'axios';
import moment from 'moment';
import SdlControl from './components/common/control';
import SdlFilters from './filters';
import SdlDirectives from './directives';
import App from './App.vue';
import { addEntryPoint, router } from './router';
import Store from './vuex/store';
import { i18n } from './i18n';
import '../static/bootstrap/css/bootstrap.min.css';
import '../static/css/custom.css';
import '../static/css/sdl.css';
import '../static/css/realgrid-style.css';
import '../static/bootstrap/js/bootstrap.bundle.min';

import api from './service';
import SDLUtil from '@/utils/SDLUtil';
import RealGrid from 'realgrid';

const app = createApp(App);

app.use(SdlControl); // Additional components. common sdl
app.use(SdlFilters); // Additional filters. common sdl
app.use(SdlDirectives); // Additional directives. common sdl
app.use(Store);

// Additional context
app.config.globalProperties.$moment = moment;
app.config.globalProperties.$CONTEXT = SDLUtil.WEB_CONTEXT_PATH;

axios.defaults.headers.common['x-auth-token'] = localStorage.getItem('userToken');
if (localStorage.getItem('adminToken') !== null && localStorage.getItem('adminToken') !== '') {
  axios.defaults.headers.common['original-user-id'] = SDLUtil.parseJwt(localStorage.getItem('adminToken')).userId;
}

axios.interceptors.request.use(
  (config) => {
    axios.defaults.headers.common['last-access-time'] = localStorage.getItem('lastAccessTime');
    // console.log('request:', localStorage.getItem('lastAccessTime'));
    // Do something before request is sent
    if (Object.prototype.hasOwnProperty.call(config, 'data')) {
      if (Object.prototype.hasOwnProperty.call(config.data, 'labelJson')) {
        config.data.labelJson = JSON.stringify(config.data.labelJson);
      }
    }
    return config;
  },
  (error) => Promise.reject(error),
);

axios.interceptors.response.use(
  (response) => {
    if (response.headers.date !== null && response.headers.date !== '') {
      localStorage.setItem('lastAccessTime', new Date(response.headers.date).getTime());
      // console.log('resonse:', localStorage.getItem('lastAccessTime'));
    }

    if (Object.prototype.hasOwnProperty.call(response.data, 'error')) {
      /*
       * Add code number below if error message is passed to login after error message during certain error code
       */
      const loginErrCodes = ['187', '190', '191', '192', '193', '194', '195', '199', '200'];

      // 500 is excluded for error checking when localhost.
      if (window.location.hostname !== 'localhost') {
        loginErrCodes.push('500');
      }
      if (loginErrCodes.includes(String(response.data.error.code)) && router.currentRoute.value.fullPath.indexOf('/login') === -1) {
        // Do not process logout when there is a general error
        if (String(response.data.error.code) !== '500') api.logout();
        document.location = `${SDLUtil.WEB_CONTEXT_PATH}/error?code=${response.data.error.code}&redirect=${router.currentRoute.value.fullPath}`;
      }
      return Promise.reject(Object.assign(response, new Error(response.data.error.message)));
    }
    return response;
  },
  (error) => Promise.reject(error),
);

// axios.get('/static/dummy/allMenuPagePaths.json')
axios
  .get(`${SDLUtil.API_URL}/auth/noauth/all-menu-page-paths`)
  .then(({ data }) => {
    addEntryPoint(data).then(() => {
      app.use(i18n);
      app.use(router);
      app.mount('#app');
    });
  })
  .catch((err) => {
    // TODO network error processing
    console.error(err);
    window.location = `${SDLUtil.WEB_CONTEXT_PATH}/static/error.html`;
  });

  RealGrid.setLicenseKey('upVcPE+wPOmtLjqyBIh9RkM/nBOseBrflwxYpzGZyYm9cY8amGDkiMnVeQKUHJDjW2y71jtk+wteqHQ1mRMIXzEcGIrzZpzzNTakk0yR9UcO/hzNodVsIiqQNVtxmmYt');
  
  //https://docs.realgrid.com/refs/Interface/GridOptions
  RealGrid.setDefault({   
    edit: {
      editable: false,
      commitByCell: true,
      commitWhenLeave: true,
      columnEditableFirst: true
    }, 
    copy: {enabled: true},
    paste: {enabled: false},
    
    
    checkBar: { visible: false, showAll: false },
    stateBar: {
      visible: false
    },
    header: {
      height: 30
    },
    footer: {
      visible: false
    },
    display: {
      rowHeight: 30,
      rowResizable: true,
      eachRowResizable: true,
      columnMovable: false,
      showEmptyMessage:true,
      emptyMessage: "NO DATA",
    }
  });