import { Injectable } from '@angular/core';
import { environment } from '../../../environments/environment';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';

import { JwtService } from '../services';

export interface headersConfig {
    'Content-Type': string;
    'Accept': string;
    'Authorization'?: string;
}

@Injectable({ providedIn: 'root' })
export class HttpTokenInterceptor implements HttpInterceptor {
    constructor(private jwtService: JwtService) { }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        var config: headersConfig = {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        };
        //Basic cmFtcGV1cjpES3hwMjRQUw==
        //console.log(req.headers.get('Authorization'));
        const basic = req.headers.get('Authorization');
        if (basic == 'Basic cmFtcGV1cjpES3hwMjRQUw==') {
            config['Authorization'] = `${basic}`;
        } else {
            const token = this.jwtService.getToken();
            if (token) {
                config['Authorization'] = `Token ${token}`;
            } else if (environment.use_api_key) {
                config['Authorization'] = `Api-Key ${environment.api_key}`;
            }
        }
        const request = req.clone({ setHeaders: <any>config });
        return next.handle(request);
        /*
        const headers= new HttpHeaders()
            .set('Content-Type', 'application/json')
            .set('Accept', 'application/json');
        const token = this.jwtService.getToken();
        if (token) {
            headers.set('Authorization', `Token ${token}`);
        } else if (environment.use_api_key) {
            headers.set('Authorization', `Api-Key ${environment.api_key}`);
        }
        const request = req.clone({ setHeaders: headers });
        return next.handle(request);
        */
    }
}