import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Router } from '@angular/router';
import { apiUrl } from '../_resources/api-url.properties';
import { routePath } from '../_resources/route-path.properties';
import { ProvidersService } from '../providers.service';
import { BehaviorSubject, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { AuthenticationDto } from 'src/app/_dto/authentication.dto';
import { TokenDto } from 'src/app/_dto/token.dto';


/*
    Created By  : Arun Joy
    Created On  : 14-01-2020
    Created For : Created for getting authentication data from authentication API.
*/

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  headers: HttpHeaders = new HttpHeaders();

  environment: any;
  firebaseToken: string = ''

  currentUserShortInfo: { userId: string, userName: string, userImagePath: string } = { userId: '', userName: '', userImagePath: '' };
  private currentUserSubject: BehaviorSubject<any>;
  public currentUser: Observable<any>;

  constructor(
    private http: HttpClient,
    private router: Router,
    private conn: ProvidersService
  ) {
    this.environment = this.conn.environment;
    this.currentUserSubject = new BehaviorSubject<any>(localStorage.getItem('authtoken') ? true : false);
    this.currentUser = this.currentUserSubject.asObservable();
  }

  public get currentUserValue(): any {
    return this.currentUserSubject.value;
  }

  signIn(param: AuthenticationDto)
    : Promise<TokenDto> {
    this.headers.append('Content-Type', 'application/json');
    this.headers.append('emailid', param.username);
    return (this.http.post<TokenDto>(`${this.environment.apiUrl}/${apiUrl.login}`, param)
      .pipe(map(user => {
      //  console.log("=======user========", user)
        if (user && user != null) {
       //   console.log("=======user======1==", user)
          // if (user.accessToken)
            this.currentUserSubject.next(user);
          // else
          //   return user;
        }
        return user;
      })))
      .toPromise();
  }

  getUserModule(param: AuthenticationDto): Promise<void> {
    return this.http.get<any>(`${this.environment.apiUrl}/${apiUrl.login}`, { headers: { 'emailid': param.username } }).toPromise();
  }

  getUserInfo(): Promise<{ userId: string, userName: string, userImagePath: string, userEmail: string, userMobile: string }> {
    return this.http.get<any>(`${this.environment.apiUrl}/${apiUrl.userInfo}`).toPromise();
  }

  facebookSignIn() {
    var myWindow = window.open(`${this.environment.apiUrl}/${apiUrl.facebookSignIn}`, "_system", "width=400,height=400,toolbar=yes,scrollbars=yes,resizable=yes");
    // console.log("====my window", myWindow);

    let timer = setInterval(() => {
      if (myWindow.closed) {
        clearInterval(timer);
        let token = localStorage.getItem("authtoken");
        if (token) {
          this.router.navigate([routePath.dashboard]);
        }
      }
    }, 1000);

  }

  googleSignIn() {
    var myWindow = window.open(`${this.environment.apiUrl}/${apiUrl.googleSignIn}`, "_system", "width=400,height=400,toolbar=yes,scrollbars=yes,resizable=yes");
    // console.log("====my window", myWindow);

    let timer = setInterval(() => {
      if (myWindow.closed) {
        clearInterval(timer);
        let token = localStorage.getItem("authtoken");
        if (token) {
          this.router.navigate([routePath.dashboard]);
        }
      }
    }, 1000);

  }

  async logOut() {
    localStorage.setItem('authtoken', '');
    localStorage.setItem('refreshtoken', '');
    localStorage.setItem('emailId', '');
    localStorage.setItem('module', '');
    await localStorage.removeItem('authtoken');
    localStorage.removeItem('refreshtoken');
    localStorage.removeItem('emailId');
    localStorage.removeItem('module');
    localStorage.removeItem('passwordVersion');
    this.currentUserSubject.next(null);
    // await this.router.navigate([routePath.login]);
    // location.reload();
    // this.navCntrl.navigateBack('/Login');
    let institute = localStorage.getItem("institute");
    this.router.navigate([routePath.login]);
  }


  async getUserImage(imageName: string): Promise<any> {
    return this.http.get(`${this.environment.apiUrl}/${apiUrl.userImageUpload}/${imageName}`, { responseType: 'blob' }).toPromise();
  }

  async changePassword(body, id?): Promise<any> {
    return await this.http.patch<any>(`${this.environment.apiUrl}/${"user/change-password"}`, body).toPromise();
  }

  async patchToken(): Promise<any> {
   // console.log(this.firebaseToken, 'firebase token');

    return await this.http.patch<any>(`${this.environment.apiUrl}/${"user/firebase"}`, { token: this.firebaseToken }).toPromise();
  }

  // async validatePassword(authCredentials:AuthenticationDto)
  // {
  //   console.log("===validatePassword authCredentials====",authCredentials);
  //   return this.http.get(`${this.environment.apiUrl}/${apiUrl.validatePassword}/${authCredentials}`).toPromise();
  // }

  async sendOtp(email,FR): Promise<any> {
    console.log("==",email)
    return await this.http.post<any>(`${this.environment.apiUrl}/${"auth/otp"}/${FR}`,email).toPromise();
  }

  async verifyOtp(body,FR): Promise<any> {
    return await this.http.post<any>(`${this.environment.apiUrl}/${"auth/verifyOtp"}/${FR}`,body).toPromise();
  }

  async forgotPassword(body): Promise<any> {
    return await this.http.post<any>(`${this.environment.apiUrl}/${"auth/forgot-password"}`,body).toPromise();
  }

}
