import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

import { LoadingController, AlertController, Events } from 'ionic-angular';
import { AbstractControl, ValidatorFn } from '@angular/forms'

@Injectable()
export class Myservice {

  // base_url = 'http://techlabz.in/bmd_new/'
  base_url = 'http://192.168.140.20/CMC/'
  webservice_url = this.base_url + 'web_service/'


  loader: any;
  alert: any;
  post_url: any;
  data: any;
  result: any;
  msg_push: any;

  constructor(public http: Http, public loadingCtrl: LoadingController, public alertCtrl: AlertController, public events: Events) { }

  show_loader() {
    this.loader = this.loadingCtrl.create({
      content: ""
    });
    this.loader.present();
  }

  show_alert(title, message) {
    this.alert = this.alertCtrl.create({
      title: title,
      subTitle: message,
      // message: message,
      buttons: ['OK']
    });
    this.alert.present();
  }

  hide_loader() {
    this.loader.dismissAll();
  }

  load_post(post_data, fn_name) {
    post_data.secret_key = 'My_key';
    post_data = JSON.stringify(post_data);
    this.post_url = this.webservice_url + fn_name;
    // let headers = new Headers();
    // headers.append('X-API-KEY', 'key_test');
    // let options = new RequestOptions({ headers });
    return this.http.post(`${this.post_url}`, `${post_data}`).map(res => res.json());
  }

  get_data(fn_name) {
    return this.http.get(this.webservice_url + fn_name)
      .map(res => res.json());
  }

  get_dataById(fn_name, id) {
    return this.http.get(this.webservice_url + fn_name + id)
      .map(res => res.json());
  }

  fileUpload(data, fn_name) {
    var post_url = this.webservice_url + fn_name;
    return this.http.post(post_url, data)
      .map(res => res.json());
  }

  get_baseurl() {
    return this.base_url;
  }

  checkLimit(min: number, max: number): ValidatorFn {
    return (c: AbstractControl): { [key: string]: boolean } | null => {
      if (c.value && (isNaN(c.value) || c.value < min || c.value > max)) {
        return { 'range': true };
      }
      return null;
    };
  }

}