import { Http } from '@angular/http';
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { Observable} from 'rxjs/Rx';
import { LoadingController, ToastController } from 'ionic-angular';
import { AbstractControl, ValidatorFn } from '@angular/forms'

@Injectable()
export class CommonProvider {

	site_url:string;
	webservice_url:string;
	loader:any;
	headers:any;

	constructor(
		public http: Http, 
		public loadingCtrl: LoadingController, 
		public toastCtrl: ToastController
	) {
	  this.headers = { 'X-API-KEY': 'my_key' };
	  //this.site_url = 'http://vmig.kz/vmig/';
	 
	this.site_url = 'https://techlabz.in/client/vmig_demo/';//my_key
	
	  this.webservice_url = this.site_url+'admin/index.php/Webservice_App/';
	}

	post_data(url,data){		
		//this.http.setHeader('*', 'accept', 'application-json');				
		return this.http.post(this.webservice_url+url, data,{headers:this.headers}).map(res=>res.json()).catch(initialError => {
            return Observable.throw(initialError._body);
        });
	}

	get_data(url){
		return new Promise(resolve => {
			this.show_loader();
			this.http.get(this.webservice_url+url).map(res=>{
				console.log(res);
				resolve(res);
			}).subscribe(data => {
	      		console.log(data);
		    }, err => {
		      console.log(err);
		    });
		})
	}

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

	 	setTimeout(() => {
		   this.loader.dismiss();
		   //this.presentToast("Something went wrong");
		}, 10000);
	}

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

	presentToast(message) {
	    let toast = this.toastCtrl.create({
	      message: message,
	      duration: 3000,
	      position: 'bottom'
	    });

	    toast.onDidDismiss(() => {
	      console.log('Dismissed toast');
	    });

	    toast.present();
	}

	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;
	    };
	}

}
