import { Injectable } from '@angular/core';
import { Config } from './config';
import { HttpLayerService } from './http-layer.service';
import { SharedService } from './shared.service';
import { EMPTY, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Router } from '@angular/router';
import { environment } from '../../environments/environment';
import { ToastrService } from '../common-components/toastr/toastr.service';

/**
 * api: string species the API
 * payload: the requested data to the api
 * method: method of the API request
 * loader: to display loader
 * type: whether local json or actually api
 * hideErrorMessage: to display error message
 */
export class RequestPayLoadFormat {
  api: string;
  payLoad?: object;
  method: 'post' | 'get' | 'postText' | 'postFile' | 'postDownload';
  loader?: boolean;
  type: 'API' | 'JSON';
  hideErrorMessage?: boolean;
  options?: object;
  params?: object;
  formData?: any;
  loadURL?: any

}

@Injectable({
  providedIn: 'root'
})
export class CommonServiceLayerService {
  public sidebarData: any;
  constructor(
    private http: HttpLayerService,
    private router: Router,
    public sharedService: SharedService,
    private _toast: ToastrService,
  ) {
  }

  API_REQUEST(request: RequestPayLoadFormat): Observable<any> {
    try {
      // console.log('request: ', request);
      const URL = request.loadURL ? request.loadURL : Config[request.type][request.api];
      return this.http[request.method](URL, request).pipe(map((res: any) => {
        if (res.status === 401) {
          this._toast.toast('error', environment.sessionInvalidMessage, res.statusText, true);
          // const alertConf: AlertConfig = { type: 'error', title: environment.sessionInvalidMessage, body: res.statusText };
          // this.alert.open(alertConf);
          this.logOut();
        } else {
          // console.log(res.headers.get('set-cookie'));
          return res;
        }
      }));
    } catch (error) {
      this.sharedService.internalCodeError();
      return EMPTY;
    }
  }
  public logOut() {

    localStorage.clear();
    sessionStorage.clear();
    this.router.navigate(['p/login']);
  }
  // tslint:disable-next-line:typedef
  checkRoute() {
    try {
      if (!this.sidebarData) {
        return;
      }
      setTimeout(() => {
        const url = window.location.hash.replace('#', '');
        if (!this.checkUrl(url, this.sidebarData) && url !== '/login') {
          this.router.navigate(['/landing/not-found']);
          // this.http.logOut();
          return false;
        }
        return true;
      }, 100);
    } catch (error) {
      return;
      console.log(error);

    }
  }

  // tslint:disable:typedef
  checkUrl(url, sidebar) {
    try {
      const urlArray = url.split('/');
      if (urlArray.length < 3 && urlArray[1] === 'landing') {
        return true;
      }
      for (const item in sidebar) {
        if (sidebar[item].subMenu && sidebar[item].subMenu.length) {
          // tslint:disable-next-line: forin
          for (const value in sidebar[item].subMenu) {
            if (sidebar[item].subMenu && sidebar[item].subMenu.length) {
              // tslint:disable-next-line: forin
              for (const subSubValue in sidebar[item].subMenu[value].subMenu) {
                if (sidebar[item].subMenu[value].subMenu && sidebar[item].subMenu[value].subMenu.length) {
                  if (sidebar[item].subMenu[value].subMenu[subSubValue].route === url) {
                    return true;
                  }
                }
              }
            } else {
              if (sidebar[item].subMenu[value].route === url) {
                return true;
              }
            }
          }
        } else {
          return false;
        }
      }
      return false;
    } catch (error) {
      console.log(error);
      return false;
    }
  }
}
