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


@Injectable()
export class AuthHttpInterceptor implements HttpInterceptor {

  constructor(private auth: AuthService) {
  }

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

    if (this.auth.loggedIn.hasValidSession()) {
      h = h.set('Biukop-Session', this.auth.loggedIn.session);
    }

    if (this.auth.loggedIn.hasValidMachineId()) {
      h = h.set('Biukop-Mid', this.auth.loggedIn.machineId);
    }

    const authReq = req.clone({
      headers: h,
      withCredentials: true
    });
    return next.handle(authReq).pipe(
      tap(event => {
        // console.log(event);
        if (event.type === HttpEventType.Response){
          const bs = event.headers.get('biukop-session');
          if (bs !== undefined){
            if ( this.auth.loggedIn.session !== bs ){
              this.auth.loggedIn.session = bs;
              this.auth.saveSessionInfo();
              console.log('switch session:' , bs);
            }
          }
        }
      })
    );
  }
}
