import {EventEmitter, Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {ApiV1LoginResponse} from '../models/api-v1-login-response';
import {Router} from '@angular/router';
import {PeopleModel} from '../models/people.model';
import {UserExtraModel} from '../models/user-extra.model';
import {UserExModel} from '../models/user-ex.model';
import {Observable} from 'rxjs';
import {AppConfig} from '../app.config';
import {SessionService} from './session.service';

@Injectable()
export class AuthService {

    constructor( private http: HttpClient ,
                 private router: Router,
                 private ss: SessionService,
                 private config: AppConfig) {  }

    isAuthenticated(): boolean  {
      return this.ss.isLoggedIn();
    }

    login(email: string, password: string): void {
      this.http.post<ApiV1LoginResponse>(this.config.apiUrl + 'login', {u: email, p: password}).subscribe(
        responseData => {
                const sfm = new ApiV1LoginResponse({
                  session: responseData['Biukop-Session'],
                  login: responseData.login,
                  machineId: responseData['Biukop-Mid'],
                  sessionExpire: responseData.sessionExpire,
                  role: responseData.role,
                  User: responseData.User? new PeopleModel(responseData.User) : new PeopleModel({}),
                  UserExtra: responseData.UserExtra? new UserExtraModel(responseData.UserExtra) : new UserExtraModel({}),
                  UserEx: responseData.UserEx ? new UserExModel(responseData.UserEx) : new UserExModel(),
                });
                this.ss.login(sfm);
                this.ss.saveSessionInfo();
         },
        error => {
          this.ss.login( new ApiV1LoginResponse({}) ) ;
        }
      );
    }

    logout(): void {
       this.ss.logout();
    }

    public getUrl(key: string): string{
      return this.config.getUrl(key);
    }

    // whether a specific login id is available
    public LoginAvailable(v: string): Observable<boolean> {
      return this.http.get<boolean>(this.getUrl('login-available/' + v));
    }

}
