import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams,AlertController } from 'ionic-angular';
import {Validators, FormBuilder, FormGroup, FormControl,FormArray } from '@angular/forms';
import { Storage } from '@ionic/storage';
import {Myservice} from '../../providers/myservice';
import { FileTransfer, FileUploadOptions, FileTransferObject } from '@ionic-native/file-transfer';
import { File } from '@ionic-native/file';
import { ImagePicker } from '@ionic-native/image-picker';

@IonicPage()
@Component({
  selector: 'page-editoffers',
  templateUrl: 'editoffers.html',
})
export class Editoffers {
	tested:any;
	todo = {}
	services_offered:any;
	user_data:any;
	base64Image: any;
	profile_pic: any;
	single_offers: any;
	today_date: any;
	offer_id: any;
	price_val:any=0;
	private editoffersForm : FormGroup;
	
	constructor(public navCtrl: NavController, public navParams: NavParams, private formBuilder: FormBuilder, public storage: Storage, private myservice: Myservice, private imagePicker: ImagePicker,private transfer: FileTransfer, private file: File,private alertCtrl: AlertController) {
	
		this.offer_id= this.navParams.get('id')
		var tdyDate = new Date();
		var nextDays = new Date(tdyDate);
		nextDays.setDate(tdyDate.getDate());
		this.today_date = nextDays.toISOString();
		this.get_single_offer()
		this.storage.get('user_data').then((user_data) => {
				if(user_data){
					this.user_data=user_data
					console.log(this.user_data);
					this.get_services()
				}
		})
		this.editoffersForm = this.formBuilder.group({ 
				//garage_services_id: ['',  Validators.compose([Validators.required, Validators.minLength(1), Validators.maxLength(3)])],
				discount: ['', Validators.required ],
				price: ['', Validators.required ],
				description: ['', Validators.required ],
				expiry_date: ['', Validators.required ]
			});
		
	}
	

	ionViewDidLoad() {
		console.log('ionViewDidLoad Editoffers');
	}

	back(){
		this.navCtrl.pop();
	}

	
	get_services(){
		this.myservice.show_loader();
		this.myservice.load_get('get_selected_services/id/'+this.user_data.id).subscribe(data => {
			this.myservice.hide_loader();
			if(data.status == 'success'){
				this.services_offered = data.result;
			}
		});
	}	
	
	get_single_offer(){
		this.myservice.show_loader();
		this.myservice.load_get('get_single_offer/id/'+this.offer_id).subscribe(data => {
			this.myservice.hide_loader();
			if(data.status == 'success'){
				this.single_offers = data.data;
				console.log(this.single_offers)
				this.price_val = this.single_offers.total_price;
				this.profile_pic = this.single_offers.img;
				this.editoffersForm.patchValue(this.single_offers);
				
			}
		});
	}
	
	
	check_discount(val){
		console.log(val);
		if((val.target.value > 100) || (val.target.value <=0)){
			console.log(this.editoffersForm.value.discount)
			this.editoffersForm.value.discount = 0;
			 
			   this.editoffersForm.controls['discount'].patchValue('');
			this.myservice.show_alert("Error", "Please enter a valid value");
		}
	}
	
	addOffers(){
		 
		var num = parseInt(this.editoffersForm.controls['price'].value)
		var val = ((num*20)/100)+num;
		this.editoffersForm.controls['price'].patchValue(val)
	var obj = Object.assign(this.editoffersForm.value,{'total_price' : this.price_val,'garage_id' : this.user_data.id})
		if(this.base64Image) {
			console.log("offer img" ,this.base64Image)
			this.load_post_file(this.base64Image, this.editoffersForm.value, "addOffers");
		}
		else {
	
			this.myservice.show_loader();
			this.myservice.load_post(this.editoffersForm.value,'addOffers').subscribe(data => {
				this.myservice.hide_loader();
				if(data.status == 'success'){
					this.navCtrl.push('Viewoffers')
				}
				else{
					this.myservice.show_alert("Error", data.message);
				}
			}); 
		}
	}
	
		  load_post_file(imageURI, post_data, fn_name) {
	  console.log(imageURI);
        let ft = this.transfer.create();
        let filename = imageURI.substr(imageURI.lastIndexOf('/')+1);
        let options = {
            fileKey: 'file',
            fileName: filename,
            mimeType: 'image/jpeg',
            chunkedMode: false,
            headers: {
                'Content-Type' : undefined
            },
            params: post_data
        }; 
        //ft.onProgress(this.onProgress);
		this.myservice.show_loader();
        ft.upload(imageURI, this.myservice.webservice_url+fn_name, options, false)
        .then((result: any) => {
            //this.success(result);
			this.myservice.hide_loader();
			console.log(result);
			  var res =JSON.parse(result.response);
				if(res.status == "failed") {
	  			this.myservice.show_alert("Error!", result.message);
			}
			else {
				
				this.myservice.show_alert("Success!", res.message);
				this.navCtrl.push('Viewoffers')
			}
        }).catch((error: any) => {
            //this.failed(error);
			console.log(error);
			//this.result = error;
			this.myservice.hide_loader();
			this.myservice.show_alert("Error!", 'Error occured. Please try again');
        });
		//console.log(this.result); 
		//return this.result;
  }
	
	uploadPicture(){
	    var options ={	maximumImagesCount:1,
						width:750,
						height: 338,
						quality: 100
					}
		this.imagePicker.getPictures(options).then((results) => {
 
			for (var i = 0; i < results.length; i++) {
				console.log('Image URI: ' + results[i]);
				if(results[i]){
					this.base64Image = results[i];
					this.profile_pic = results[i];
				}
			}
		}, (err) => { });
	}
	
	 date_fetch(val){
		console.log(val);
	 }
	
	get_price(){
		 
	  
		var labour_price = this.editoffersForm.controls['price'].value;
		var amounts = parseInt(labour_price);
		 
		this.price_val = 0;
		 
			 
			 
				 
			//	if((this.tested > 100) || (this.tested <=0))
				//	this.price_val = ((amounts*this.tested)/100)+amounts;
			 
			if(amounts>0){
				console.log(amounts);
				this.price_val = amounts+parseInt(this.price_val);
				
			}
			
			this.price_val = ((this.price_val*20)/100)+this.price_val;
						
			  
	}
	
	get_discount(){
		 
		if(this.editoffersForm.controls['price'].value >0){
			this.price_val = parseInt(this.editoffersForm.controls['price'].value)
			this.price_val = ((this.price_val*20)/100)+this.price_val;
			var discount_price = this.editoffersForm.controls['discount'].value;
			var amounts = parseInt(discount_price);
			console.log("price" , this.price_val)
			console.log("discount price" , amounts)
			if((amounts < 100) || (amounts >0)){
				this.price_val = this.price_val - ((this.price_val*amounts)/100)
				console.log("discount val" ,this.price_val)
			}
		}else{
			this.editoffersForm.controls['discount'].patchValue('');
			this.myservice.show_alert("Error", "Please enter a valid regular price");
		}
	}
	
	get_total(){
		 
		this.price_val = 0;
		
			this.price_val = parseInt(this.price_val)+parseInt(this.tested);
		
		console.log('price_val',this.price_val);
	}
	
	delete_offer(){
		
		let alert = this.alertCtrl.create({
			title: 'Delete Offer',
			message: 'Sure you want to delete offer?',
			buttons: [
			  {
				text: 'Back',
				role: 'cancel',
				handler: () => {
				  console.log('Back clicked');
				}
			  },
			  {
				text: 'Delete Offer',
				handler: () => {
					this.delete_offers()
				}
			  }
			]
		});
		alert.present();

	}
	
	delete_offers(){
		this.myservice.show_loader();
		this.myservice.load_get('delete_offer/id/'+this.offer_id).subscribe(data => {
			this.myservice.hide_loader();
			if(data.status == 'success'){
				this.navCtrl.setRoot('Viewoffers')
				
			}
		}); 
	}
	 

}
