import axios from 'axios';
import qs from 'qs';
import { toastController } from '@ionic/core';
import { TocStore } from '../stores/toc.store';
import { EnvironmentConfigService } from '.';
import { TokenService } from './token.service';
export class HttpService {
  constructor() { }
  static getInstance() {
    if (!HttpService.instance) {
      HttpService.instance = new HttpService();
    }
    return HttpService.instance;
  }
  static init() {
    var sparkleConfig = EnvironmentConfigService.getInstance().get('sparkle');
    this.http = axios.create({
      baseURL: sparkleConfig.apiUrl,
      headers: {
        'Content-Type': 'application/json',
      },
      timeout: 30000,
      paramsSerializer: function (params) {
        return qs.stringify(params, {
          encode: false,
        });
      },
    });
    this.http.interceptors.request.use(async function (config) {
      let token = await TokenService.getInstance().getToken();
      if (token) {
        config.headers.common['Authorization'] = 'Bearer ' + token;
      }
      // //config.headers.common['.AspNetCore.Culture'] = sparkle.utils.getCookieValue('Sparkle.Localization.CultureName');
      config.headers.common['Sparkle.CourseId'] = sparkleConfig.courseId;
      console.log(TocStore.state.pageInfo);
      if (TocStore.state.pageInfo) {
        config.headers.common['Sparkle.CourseModuleId'] = TocStore.state.pageInfo.courseModuleId;
        config.headers.common['Sparkle.SessionId'] = TocStore.state.pageInfo.sessionId;
        config.headers.common['Sparkle.PageId'] = TocStore.state.pageInfo.pageId;
      }
      return config;
    }, function (error) {
      return Promise.reject(error);
    });
    this.http.interceptors.response.use(async (response) => {
      if (response.data.Message) {
        const toast = await toastController.create({
          message: response.data.Message,
          duration: 3000,
        });
        toast.present();
      }
      return response.data.Failed ? null : response.data;
    }, async (error) => {
      if (error.response && error.response.data && error.response.data.ErrorMessage) {
        // The request was made and the server responded with a status code
        // that falls out of the range of 2xx
        const toast = await toastController.create({
          message: error.response.data.ErrorMessage,
          duration: 3000,
        });
        toast.present();
        return Promise.reject(error);
      }
      else if (error.response && error.response.data && error.response.status == 400) {
        // The request was made and the server responded with a status code
        // that falls out of the range of 2xx
        const toast = await toastController.create({
          message: error.response.data.Message,
          duration: 3000,
        });
        toast.present();
        return Promise.reject(error.response.data);
      }
      else if (error.response && error.response.data && error.response.data.Message) {
        // The request was made and the server responded with a status code
        // that falls out of the range of 2xx
        const toast = await toastController.create({
          message: error.response.data.Message,
          duration: 3000,
        });
        toast.present();
        return Promise.reject(error);
      }
      else if (error.request) {
        // The request was made but no response was received
        // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
        // http.ClientRequest in node.js
        console.log(error.request);
      }
      else {
        const toast = await toastController.create({
          message: 'Unknown Error',
          duration: 3000,
        });
        toast.present();
      }
      setTimeout(() => { }, 1000);
      return Promise.reject(error);
    });
  }
}
