import {Component, OnInit} from '@angular/core';
import {Router, ActivatedRoute} from '@angular/router';

import {AlertService} from '../core/alert.service';
import {AuthenticationService} from '../core/authentication.service';
import {CartService} from '../core/cart.service';
import {AppConfig} from '../config/app.config';

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

export class LoginComponent implements OnInit {
    model: any = {};
    loading = false;
    returnUrl: string;

    constructor(private route: ActivatedRoute,
                private router: Router,
                private cartService: CartService,
                private authenticationService: AuthenticationService,
                private alertService: AlertService) {
    }

    ngOnInit() {
        // reset login status
        this.authenticationService.logout();

        // get return url from route parameters or default to '/'
        this.returnUrl = AppConfig.routes.home || '/';
    }

    login() {
        this.loading = true;
        this.authenticationService.login(this.model.username, this.model.password)
            .subscribe(
                data => {
                    this.router.navigate([this.returnUrl]);
                    this.loading = false;
                },
                error => {
                    this.loading = false;
                    if (typeof error === 'string') {
                        this.alertService.error(error);
                    } else {
                        this.alertService.error('Connection error');
                    }
                });
    }
}
