import {Injectable} from '@angular/core';
import {HttpEvent, HttpEventType, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse} from '@angular/common/http';
import {Observable} from 'rxjs';
import {tap} from 'rxjs/operators';
import {SessionService} from '../service/session.service';


@Injectable()
export class AuthHttpInterceptor implements HttpInterceptor {

  constructor(private ss: SessionService) {
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    let h = req.headers;

    if (this.ss.SessionId !== '') {
      h = h.set('Biukop-Session', this.ss.loggedIn.session);
    }
    if (this.ss.MachineId !== '') {
      h = h.set('Biukop-Mid', this.ss.MachineId);
    }
    if (this.ss.SocketId !== '') {
      h = h.set('Biukop-Socket', this.ss.SocketId);
    }

    const authReq = req.clone({
      headers: h,
      withCredentials: true
    });

    const self = this;
    return next.handle(authReq).pipe(
      tap(event => {
        // console.log(event);
        if (event.type === HttpEventType.Response){
          const bs = event.headers.get('biukop-session');
          self.setSession(bs);
          const mid = event.headers.get('biukop-mid');
          self.setMachineId(mid);
        }
      })
    );
  }

  public setSession(bs: string): void {
    // console.log('receive session:' , bs);
    if (bs){
      if ( this.ss.SessionId !== bs ){
        this.ss.SessionId = bs;
        console.log('switch session:' , bs);
      }
    }
  }

  public setMachineId(mid: string): void{
    // console.log('receive mid:' , mid);
    if ( mid && mid !== '' ){
      if ( this.ss.MachineId !== mid ){
        this.ss.MachineId = mid;
        console.log('switch machine id:' , mid);
      }
    }
  }


}
