import {HttpClient, HttpErrorResponse, HttpHeaders} from '@angular/common/http';
import {Injectable} from '@angular/core';
import {map, tap} from 'rxjs/operators';
import {Authorization} from '../models/Authorization';
import {AppService} from './app.service';
import { LocalUserDTO} from "../models/enea/LocalUserDTO";

import {Observable} from "rxjs";
import { UtilsService } from './utils.service';

@Injectable({
    providedIn: 'root'
})
export class UserService {

    constructor(private http: HttpClient, private app: AppService, private utils: UtilsService) {
    }

    login(username: string, password: string) {

        const httpOptions = {
            headers: new HttpHeaders({'Content-Type': 'application/json'})
        };

        return this.http.post("lecservice/auth/authenticate", {username: username, password: password}, httpOptions)
            .pipe(
                tap(
                    (serviceResponse: any) => {
                        if (!serviceResponse.success)
                            throw new Error("Authentication failed.");

                        this.app.setAuthorization(
                            new Authorization({
                                authenticated: true,
                                token: serviceResponse.result.token,
                                user: serviceResponse.result.user
                            })
                        );
                    })
            );
    }

    loginWithToken(token: string) {

        const httpOptions = {
            headers: new HttpHeaders({'Content-Type': 'application/json'})
        };
        console.log(token);
        return this.http.post("/lecservice/auth/authenticateWithToken", {token: token}, httpOptions)
            .pipe(
                tap(
                    (serviceResponse: any) => {
                        if (!serviceResponse.success){
                            this.utils.showInfoMessage ("Authenticatin with a token failed!");
                            throw new Error("Authentication failed.");
                        }
                       
                        this.app.setAuthorization(
                            new Authorization({
                                authenticated: true,
                                token: serviceResponse.result.token,
                                user: serviceResponse.result.user
                            })
                        );
                    })
            );
    }

    activate(code: string) {
        const httpOptions = {
            headers: new HttpHeaders({'Content-Type': 'application/json'})
        };

        return this.http.post(
            "lecservice/account/activate",
            { code }, httpOptions
        );
    }

    logout() {
        return this.http.post("lecservice/auth/logout", {})
            .pipe(
                tap(
                    (serviceResponse: any) => {

                        if (!serviceResponse.success)
                            throw new Error("Logout failed.")

                        this.app.removeAuthorization();
                    },
                    err => {
                        this.app.removeAuthorization();
                        }
                    )
            );
    }

    getUserFullName() {
        this.http.get("lecservice/admin")
            .subscribe(
                data => {
                    console.log("getUserFullName: ", data);
                    alert(data);
                },
                (err: HttpErrorResponse) => {
                    console.error('An error occurred:', err.error);
                }
            );
    }

    getCommunities(): Observable<any> {
        return this.http.get("lecservice/listCommunities");
    }

    register(model: LocalUserDTO): Observable<any> {
        return this.http.post("lecservice/register", model).pipe(
            map((response: any) => {
                return response.result
            })
        );
    }
    
    updatePassword(model: LocalUserDTO): Observable<any> {
        return this.http.post("lecservice/updatePassword", model).pipe(
            map((response: any) => {
                return response.result
            })
        );
    }
    
    update(model: LocalUserDTO): Observable<any> {
        return this.http.post("lecservice/update", model).pipe(
            map((response: any) => {
                return response.result
            })
        );
    }
}
