import {Injectable} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {Http} from '@angular/http';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
import {Headers} from '@angular/http';
import {CookieService} from 'ngx-cookie-service';
import {Router} from '@angular/router';
import {User, UsersService} from './user.service';
import {TypesService} from './type.service';
import {AppService} from './app.service';


@Injectable()
export class AuthService {
  auth: AuthService;
  currentUser: any = new BehaviorSubject(false);
  cloud_token = new BehaviorSubject('');
  firebase;

  /**
   * @param {Http} http  baray darkhadt hay http estefade mishe
   * @param {CookieService} cookieService baray save kardan token
   */
  constructor(private http: Http,
              private cookieService: CookieService,
              private router: Router,
              private userService: UsersService,
              private appService: AppService,
              private typeService: TypesService,
  ) {
    this.cloud_token.subscribe(x => {
      this.firebase = x;

    });

    this.appService.register();
    this.typeService.register();
    this.userService.register();


  }

  /**
   *
   * @param username email user hast
   * @param password
   * @param type type user hast mesl dr ya parastar
   * @returns {Observable<boolean>}
   */
  login(username, password, type, cloud_token): Observable<boolean> {

    const headers = new Headers();

    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    return this.http.post('//hpen.ir/test/public_html/api/v1/login',
      'username=' + (username) + '&password=' + (password) +
      '&type=' + (type) + '&cloud_token=' + (cloud_token),
      {headers: headers})
      .map(res => res.json())
      .map(res => {
        if (res) {
          this.setToken(res['token']);
          localStorage.setItem('basics', JSON.stringify(res['basics']));
          this.currentUser.next(this.convertUserFromText(res['user']));

        }
        return this.isLoggedIn();
      });
  }


  /**
   * auth token
   */
  getToken(): string {
    return this.cookieService.get('token');
  }

  /**
   * auth token
   */
  setToken(token: string) {

    if (token === '') {
      this.cookieService.delete('token');
    } else {
      this.cookieService.set('token', token);

    }

  }

  isLoggedIn(): boolean {
    return !!this.currentUser.getValue();
  }

  logout() {
    this.setToken('');
    this.currentUser.next(false);
    this.router.navigateByUrl('/auth/signin');

  }

  convertUserFromText(userString: string): User {
    const userObj = this.userService.new();
    if (userString !== 'null') {
      this.userService.convert(JSON.parse(userString), userObj);
    }
    return userObj;
  }

  /**
   *
   * @returns {Observable<boolean>}
   */
  init(cloudeToken: string): Observable<boolean> {
    const headers = new Headers();

    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    headers.append('Authorization', 'Bearer ' + this.getToken());
    return this.http.post('//hpen.ir/test/public_html/api/v1/init',
      'app_packagename=' + 'hpen_web' +
      '&app_version=' + '1' +
      '&app_sdk=' + '1' +
      '&cloud_token=' + cloudeToken
      ,
      {headers: headers})
      .map(res => res.json())
      .map(res => {
        if (res) {
          localStorage.setItem('basics', JSON.stringify(res['basics']));
          this.currentUser.next(this.convertUserFromText(res['user']));

        }
        return this.isLoggedIn();
      });
  }

  getNoAuthUrls(): string[] {
    return ['/auth/signin', '/auth/forgot'];
  }

  updateUser() {
    const id = this.currentUser.getValue().id;
    if (id) {
      this.userService.get(id, {
        include: ['messages', 'app', 'type']
      }).subscribe(user => {
        console.log('response user is', user);
        this.currentUser.next(user);

      });
    }


  }


}
