import { environment } from '../../environments/environment';

import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/toPromise';

import { TokenService, IToken } from '../token';
import { Promise, isPromiseAlike, resolve } from 'q';

const serverApiUrl = environment.serverApiUrl;

/**
* This class provides the Session service with methods to read names and add names.
*/
@Injectable()
export class SessionService {
  /**
  * Creates a new SessionService with the injected Http.
  * @param {Http} http - The injected Http.
  * @constructor
  */
  constructor(private http: Http, private tokenService: TokenService) { }
  /**
  * Returns an Promise for the HTTP POST request for create operator.
  * @return {Operator} The Observable for the HTTP request.
  */
  signUp(credentials: { email: string, password: string }): PromiseLike<boolean> {
    let headers: Headers = new Headers({
      'Content-Type': 'application/json',
      Authorization: this.tokenService.authorization
    });
    let requestOptions: RequestOptions = new RequestOptions({ headers });
    return this.http.post(
      `${serverApiUrl}/general/operator`, { operatorName: credentials.email, operatorPassword: credentials.password }, requestOptions)
      .map((res: Response) => res.json())
      // .do(data => console.log('server data:', data))  // debug
      .catch(e => this.handleError(e))
      .toPromise().then(
      (data) => this.signIn(credentials)
      );
  }
  signIn(credentials: { email: string, password: string }): PromiseLike<boolean> {
    return this.tokenService.apiOperatorToken({ operatorName: credentials.email, operatorPassword: credentials.password })
      .then(()=>{return true;});
  }


  /**
  * Handle HTTP error
  */
  private handleError(error: any) {
    let errMsg = (error.message) ? error.message :
      error.status ? `error.status - error.statusText` : 'Server error';
    console.error(errMsg); // log to console instead
    return Observable.throw(errMsg);
  }
}
