import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AlertService, AuthenticationService } from '../_services/index';
import { BaseComponent } from '../base/base.component';


@Component({
    moduleId: module.id.toString(),
    templateUrl: 'login.component.html',
    styleUrls: ['login.component.scss']
})

export class LoginComponent extends BaseComponent implements OnInit {
    // Public
    public model: any = {};
    public loading = false;

    constructor(
        private router: Router,
        private authenticationService: AuthenticationService,
        private alertService: AlertService
    ) {
      super();
    }

    ngOnInit() {
        this.authenticationService.setRedirectUrl('/admin/home');
        // If logged in, then redirect to original url
        if (this.authenticationService.isLoggedIn()) {
            this.loggedInRedirection();
        }
    }

    login() {
        this.loading = true;
        this.authenticationService.login(this.model.email, this.model.password)
            .subscribe(
                data => {
                    this.loading = false;
                    if (data.msg === this.CONSTANTS.servicesMsg.ACCESS_DENIED) {
                        this.alertService.error('Email o Password incorrectos');
                    } else {
                        if(localStorage.getItem('role') === '2') {
                            this.authenticationService.setRedirectUrl('/admin/seller/quotes');
                        }

                        this.router.navigate([this.authenticationService.getRedirectUrl()]);
                    }
                },
                error => {
                    this.loading = false;
                    if (error.status === 401) {
                      this.alertService.error('Email o Password incorrectos');
                    } else {
                      this.alertService.error('Error inesperado');
                    }
                }
            );
    }

    private loggedInRedirection() {
        this.router.navigate(['/admin/home']);
    }

    goToForgotPassword() {
        // Logic here
    }
}
