import { Injectable, Output, EventEmitter } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Storage } from '@ionic/storage';
import { Device } from '@ionic-native/device';

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

@Injectable()
export class AuthService  {

  @Output() loginOk = new EventEmitter<any>();
  public push: string = '';

  constructor(public http: HttpClient, private storage: Storage, private device: Device) {}

  /** login */
  public login(params: { rut: string, password: string, level: string }) {
    let req = this.http.post(environment.apiUrl+'users/login', params).share();

    req.subscribe(data => {
      this.loginOk.emit(data);
    });
    return req;
  }

  public version(v: string) {
    let req = this.http.post(environment.apiUrl+'versionValidate', {version: v});
    return req;
  }
  public getTerms() {
    let req = this.http.get(environment.apiUrl+'terms/url');
    return req;
  }

  /** signup */
  public register(params: any) {
    let req = this.http.post(environment.apiUrl+'users/register', params);
    return req;
  }

  public recoverPassword(rut: string) {
    let req = this.http.post(environment.apiUrl+'users/recover', {rut: rut});
    return req;
  }

  public evaluate(params: any) {
    let req = this.http.post(environment.apiUrl+'users/evaluate', params);
    return req;
  }

  public setToken(token) {
    this.storage.set('token', token);
  }
  public getStates() {
    let req = this.http.get(environment.apiUrl+'states');
    return req;
  }
  public getMaster(type:string) {
    let req = this.http.get(environment.apiUrl+'masterdata/'+type);
    return req;
  }
  public getCities(id: any) {
    let req = this.http.get(environment.apiUrl+'cities/'+id);
    return req;
  }
  
  setPush(token) {
    this.push = token;
  }

  sendPushToServer(id:number) {
    this.http.post(environment.apiUrl+'users/device', {
      id: id,
      token: this.push,
      os: this.device.platform,
      osversion: this.device.version,
      appversion: environment.version
    }).subscribe((ok) => {
      console.log('push ok', ok);
    }, (err) => {
      console.log('push err', err);
    });
  }

  /** logout */
  logout() {}
}
