import {HttpErrorResponse} from '@angular/common/http';
import {Component, OnInit} from '@angular/core';
import {Router} from '@angular/router';
import {UserService} from 'src/app/services/user.service';
import {MessageService} from "primeng/api";
import {ActivatedRoute} from '@angular/router';

import {UtilsService} from 'src/app/services/utils.service';

@Component({
    selector: 'app-login',
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
    public loading: boolean = false;
    /*public username: string = "utente.ec@test.it";
    public password: string = "energyCommunity";*/
    public username: string = "";
    public password: string = "";
    private JWT: string = "";
    public local: boolean = false;

    constructor(
        private router: Router,
        private userService: UserService,
        private messageService: MessageService,
        private route: ActivatedRoute,
        private utils: UtilsService,
    ) {
    }

    ngOnInit(): void {
        this.route.queryParams
            .subscribe(params => {
                    this.JWT = params.token;
                    if (params.token) {
                        this.loginWithToken(this.JWT);
                        this.local = false;
                    }
                    else {
                        this.local = true;
                    }
                }
            );
    }

    login() {
        this.loading = true;

        this.userService.login(this.username, this.password)
            .subscribe(
                (serviceResponse: any) => {
                    this.loading = false;
                    this.router.navigateByUrl("/");
                },
                (err: HttpErrorResponse) => {
                    this.utils.showErrorMessage(err.message);
                    this.loading = false;
                    this.messageService.add({severity: 'warn', summary: 'Login', detail: err.message});
                }
            );
    }


    loginWithToken(token: string) {
        this.loading = true;

        this.userService.loginWithToken(token)
            .subscribe(
                (serviceResponse: any) => {
                    this.loading = false;
                    this.router.navigateByUrl("/");
                },
                (err: HttpErrorResponse) => {
                    this.loading = false;

                    this.messageService.add({severity: 'warn', summary: 'Login', detail: err.message});
                }
            );
    }

}
