/*
 * Copyright (C) 2017 Robert Bosch GmbH Copyright (C) 2017 Robert Bosch Manufacturing Solutions GmbH, Germany. All rights reserved.
 */

import { AfterViewInit, Component, OnDestroy } from '@angular/core';
import { Router } from '@angular/router';
import { BciSidebarService, LoggerService } from '@bci-web-core/core';

@Component({
  selector: 'bci-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss'],
})
export class LoginComponent implements OnDestroy, AfterViewInit {
  model: { tenant?: string; username?: string; password?: string } = {};
  loading = false;
  errorMsg = '';
  useTenant = true;

  constructor(private router: Router, private logger: LoggerService, private sidebarService: BciSidebarService) {}

  ngAfterViewInit() {
    this.sidebarService.setSidebarVisibility(false);
  }

  login() {
    this.logger.trace('Started login');
    this.loading = true;
    if (Math.random() <= 0.5) {
      this.logger.info('Logged in with user credentials');
      this.loading = false;
      this.router.navigate(['/']);
    } else {
      this.logger.error(`Couldn't log in with user credentials: Try again`);
      this.errorMsg =
        'Login randomly failed with the provided credentials. Please ensure customer, username and password are correct.';
      this.loading = false;
    }
  }

  logout() {
    this.logger.info('Logged out');
  }

  ngOnDestroy() {
    this.sidebarService.setSidebarVisibility(true);
  }
}
