import { Modal } from 'ngx-modialog/plugins/bootstrap';
import { HttpClient, HttpRequest } from '@angular/common/http';
import { Injectable } from '@angular/core';
import * as JWT from 'jwt-decode';
import { tokenNotExpired, JwtHelper } from 'angular2-jwt';
import { Observable, Subject } from 'rxjs';
import { ActivatedRoute } from '@angular/router';
import { JwtHelperService } from '@auth0/angular-jwt';
import { Location } from '@angular/common';




@Injectable({
  providedIn: 'root'
})

export class AuthServiceService {

  constructor(private http:  HttpClient, 
    private location: Location,
    private modal: Modal, 
    private route: ActivatedRoute) {
     }

  jwtHelper: JwtHelper = new JwtHelper();

  //user permision name
  addButton: string = 'add_user';
  editButton: string = 'edit_user';
  deleteButton: string = 'delete_uder';
  showAddBtn: boolean = false;
  showDeleteBtn:boolean = false;
  showEditBtn: boolean = false;
  showReportBtn: boolean = false;
  showPrintBtn: boolean = false;
  showPermissionsBtn: boolean = false;
  showHeaderLogin: boolean = false;
  showHeaderDashBoard: boolean = false;
  showMoreLinks:boolean = false;
  showDashboardHeader: boolean = false;
  internalHeader: boolean = false;
    
  
  end = '1990-01-01';

  arabicTemplate: boolean;
  arabicLanguage: boolean;
  englishLanguage:boolean;
  showArabicIcon:boolean;
  showEnglishIcon:boolean;

  pathApi: string = 'http://kfmc.info/back_end/api';
  pathImg: string = "http://kfmc.info/back_end/public/";
  myInnerHeight = window.innerHeight;
  imgSrc: string =  '../../assets/image/avatar.png'; //page profile default
  iconImg: string = '../../assets/image/Group 92.png';

  showSearchHeader: boolean = true;
  headereClassActive:boolean = false;
  homeActivate:boolean = true;
  cachedRequests: Array<HttpRequest<any>> = [];
  notificationLogin: boolean = true;
  checkExternalFooter: boolean = false; 
  


  parentsPage = [];
  footerData=[];
  

  dataLoginUser = {};
  
  //login function
  login(dataForm) {
    console.log(dataForm);
    return this.http.post(this.pathApi + '/login', dataForm);
  }

  //signup Function
  signUp(dataSignUp){
    console.log(dataSignUp);
    return this.http.post(this.pathApi + '/register', dataSignUp);
  }

  //return data user function
  setDataUser(user) {
    this.dataLoginUser = user.user;
    console.log('data loooogin' , this.dataLoginUser);
  }


  //Authentication
  public getToken(): string {
    return localStorage.getItem('token');
  }

  public isAuthenticated(): boolean {
    // get the token
    const token = this.getToken();
    // console.log('toooooken',this.jwtHelper.isTokenExpired(token));
    // return a boolean reflecting
    // whether or not the token is expired
    if(token){
      return this.jwtHelper.isTokenExpired(token);

    }
    return true;
  }


  public collectFailedRequest(request): void {
    this.cachedRequests.push(request);
  }


  //previous back locarion
  perviousLocation() {
    this.location.back();
  }

  //out of page
  backFromEdit() {
    const dialogRef = this.modal.alert()
    .size('sm')
    .showClose(true)
    .title('تأكيد الخروج')
    .body(`
        <h4>الخروج من هذه الصفحه ؟ </h4>
        `)
    .open();

      dialogRef.result
      .then( result => 
        this.perviousLocation()
      );
  }

  setLocalLang(){
    if(! localStorage.getItem('lang')){
      localStorage.setItem('lang', "ar");

      this.arabicTemplate = true;
      this.arabicLanguage = true;
      this.englishLanguage = false;
      this.showArabicIcon= false;
      this.showEnglishIcon=true;
    }else{
      if(localStorage.getItem('lang')=='ar'){

        this.arabicTemplate = true;
        this.arabicLanguage = true;
        this.englishLanguage = false;
        this.showArabicIcon= false;
        this.showEnglishIcon=true;
      }else if(localStorage.getItem('lang')=='en'){
        this.arabicTemplate = false;
        this.arabicLanguage = false;
        this.englishLanguage = true;
        this.showArabicIcon = true;
        this.showEnglishIcon = false;
      }
    }
  }

  //language content
  onLanguageContent(typeLang:string) {
    localStorage.setItem('lang', typeLang);
    this.setLocalLang();
    //window.location.reload();
  }




  //get footer list 
  onGetFooterData(typePageFooter:string) {
    if(typePageFooter == 'external') {
      return this.http.get(this.pathApi + '/get_footers_links/1');
    } else if(typePageFooter == 'internal' || 'dashboard') {
      return this.http.get(this.pathApi + '/get_footers_links');
    }
  }

   writeHijri(date, lang, type) {
    
    lang = lang || 'en';
    
    var options = {
      year: 'numeric', month: 'long', day: 'numeric'
    };

    var days = ['الأحد', 'الأثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعه', 'السبت'];

     if(type == 'system') {
      var date = date;
     } else if(type == 'header') {
       date = new Date();
       var dayName = days[date.getDay()];
     }
    //var date = date || new Date();
    if(dayName) {
      return dayName + ' ' + date.toLocaleString(lang + '-u-ca-islamic', options);
    } else {
      return date.toLocaleString(lang + '-u-ca-islamic', options);
    }
  }


}
