import { Component, Input, Output, EventEmitter } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
import { CheckAuthStatus } from '../services/checkAuthStatus/checkAuthStatus.service';
import { ModuleOptions } from '../services/moduleoptions/moduleoptions.service';
import { I18nService } from '../services/i18n/i18n.service';

/* tslint:disable */
@Component({
  selector: 'innotec-login',
  templateUrl: './innoteclogin.component.pug',
  styleUrls: [ './innoteclogin.component.sass' ],
  host: {
    '(document:keyup)': '_keyup($event)'
  }
})
/* tslint:enable */
export class InnotecLogin {
  username: any;
  password: any;
  error: boolean;

  @Output() goSocial = new EventEmitter<string>();

  constructor(private http: Http,
              private options: ModuleOptions,
              private auth: CheckAuthStatus,
              public i18n: I18nService) {
  }

  public gotoSocial(ev) {
    this.goSocial.emit(ev);
  }

  public goToRegistration() {
    window.location.href = this.options.get().userregisterurl;
  }

  public login_Innotec(username, password) {
    let authorization = this.options.get().clientid + ':' + this.options.get().clientsecret;
    let headers = new Headers();

    headers.set('Authorization', authorization);

    return this.http.post(this.options.get().endpoint, { username, password }, { headers })
      .toPromise()
      .then(res => {
        this.auth.setLoginCookie(res.json(), 'innotec');
      }, err => this.error = true);
  }

  private _keyup(key) {
    if (key.keyCode === 13 && this.username && this.password) {
      this.login_Innotec(this.username, this.password);
    }
  }
}
