import { Injectable } from '@angular/core';
import { StorageService } from './storage.service';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { LoginUserRespose, UserForm, UserSession } from '../models/user.model';
import { environment } from 'src/environments/environment';
import { HttpService } from './http.service';
import { BehaviorSubject } from 'rxjs';
import { AuthConnstants } from '../config/auth-constants';
import { AlertController } from '@ionic/angular';
import { SessionStore } from '../store/session.service';
import { AESEncrypt } from '../services/aesencrypt.service';
import { CookieService } from 'ngx-cookie-service';
import { RocketChatClientService } from '../services/socket/rocket-chat-client.service';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  userData$ = new BehaviorSubject<any>('');
  userId$ = new BehaviorSubject<any>('');
  headers: HttpHeaders;
  public ValidatedUser: UserSession;
  public ValidatedUserChat:any;
  opts:any;

  constructor(
    private http: HttpClient,
    private httpService: HttpService,
    private storageService:StorageService,
    public alertController: AlertController,
    private aesencrypt: AESEncrypt,
    private cookieService: CookieService,
    ) {

      this.headers = new HttpHeaders();

      if (SessionStore.exist) {
        this.ValidatedUser = SessionStore.user
      }

      if (localStorage.getItem("userChat") != null) {
        this.ValidatedUserChat = JSON.parse(localStorage.getItem('userChat'));
      }

    }

    async login(user: UserForm, {saveSession = true}): Promise<LoginUserRespose> {
      user.BasicAuthKey = 'Basic ' + btoa(user.username + ':' + this.aesencrypt.encrypt(user.password,user.username ));

      this.headers = this.headers.set('Authorization', user.BasicAuthKey);
      this.opts = {
        headers: this.headers,
      }

      let response: any;

      try {
        response = await this.http.post<LoginUserRespose>(environment.apiURL + "UserAuthentication/Login", '', this.opts).toPromise();
        if(saveSession) {
          this.SetSession(response, user)
        }
      } catch (error) {

      } finally {
        return response
      }

    }

    SetSession(response: LoginUserRespose, user:UserForm) {
      const session: UserSession = Object.assign(SessionStore.user, response)

      if (response) {
        if( session.RoleID == 100000014) {
          session.Profile = 'PR'
        } else if(session.RoleID == 100000011) {
          session.Profile = 'MDGPR'
        }

        session.BasicAuthKey = user.BasicAuthKey

        SessionStore.reset(session)
        this.ValidatedUser = SessionStore.user;
        this.storageService.store(AuthConnstants.USER, response);

        return true;
      }
    }

    logout() {
      this.ValidatedUser = null;
    }

    //Login to rocketChat server
    async loginChat(user: UserForm): Promise<boolean> {
      let postData = {
        "user": user.username,
        "password": user.password,
      }

      let responseChat = await this.httpService.post('login', postData).toPromise();
      if(responseChat) {
        console.log('Login to Rocket chat OK');
        this.ValidatedUserChat = responseChat;
        localStorage.setItem('userChat', JSON.stringify(responseChat));
        localStorage.setItem('Meteor.loginToken', responseChat['data'].authToken);
        localStorage.setItem('Meteor.userId',responseChat['data'].userId);
        this.cookieService.set('rc_token', responseChat['data'].authToken);
        this.cookieService.set('rc_uid', responseChat['data'].userId);
        this.storageService.store(AuthConnstants.AUTH, responseChat);
        return true;
      }
      else{
        console.log('Network error');
        this.presentAlert('Network error');
        return false;
      }
    }

    //Get user data from RocketChat | global object
    getUserData(){
      this.storageService.get(AuthConnstants.AUTH).then(res=>{
        this.userData$.next(res);
      });
    }

    logoutChat(){
      //this.storageService.clear();
      /* this.storageService.removeStorageItem(AuthConnstants.AUTH).then(res =>{
        this.userData$.next('');
        this.router.navigate(['']);
      }) */

    }
    async presentAlert(message: string) {
      const alert = await this.alertController.create({
        cssClass: 'my-custom-class',
        header: 'Mensagem do sistema',
        message: message,
        buttons: ['OK']
      });

      await alert.present();
    }
}
