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

import { Injectable, EventEmitter } from '@angular/core';
import { Router } from '@angular/router';
import { Headers, Http, RequestOptions, Response, ResponseContentType } from '@angular/http';

import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';

import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/catch';

import { TokenService } from '../../token';

const serverApiUrl = environment.serverApiUrl;
const API_IDENTIFIER = environment.apiIdentifier;

@Injectable()
export class MenuItemsService {

  constructor(private http: Http, private tokenService: TokenService, private router: Router) {
    console.log('ctro menu-items service');
  }

  getCounts(): Promise<any> {
    let headers: Headers = new Headers({
      'Content-Type': 'application/json',
      Authorization: this.tokenService.authorization
    });
    let requestOptions: RequestOptions = new RequestOptions({ headers });

    return this.http.get(
      `${serverApiUrl}/Backoffice/Menu/Counts`, requestOptions)
      .map((res: Response) => res.json())
      .map((json) => json.result)
      .catch(e => this.handleError(e))
      .toPromise();
  }
  /**
  * Handle HTTP error
  */
  private handleError(error: any) {

    if (error.status === 401) {
      this.router.navigate(['/session', 'signin']);
    }

    let errMsg = (error.msg) ? error.msg :
      error.status ? `${error.status} - ${error.statusText}` : error;
    const message = /Message: ([^\n]+)/.exec(errMsg);
    if (message) {
      errMsg = message[1];
    }
    console.error(errMsg); // log to console instead
    return Observable.throw(errMsg);
  }
}
