import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams,Events } from 'ionic-angular';
import { Validators, FormGroup, FormBuilder } from '@angular/forms'
import { Myservice } from '../../providers/myservice'
import { Storage } from '@ionic/storage';
import { Http } from '@angular/http'
import { OrderbyPipe } from '../../providers/sort-pipe';
import { user } from "../../models/mymodel";
@IonicPage()
@Component({
  selector: 'page-profile',
  templateUrl: 'profile.html',
})
export class ProfilePage {
  profileForm:FormGroup
  codes: any;
  local:user
  image:boolean = false;
  formdata = new FormData();

  constructor(public navCtrl: NavController, public navParams: NavParams, private formBuilder: FormBuilder, private myservice: Myservice, private http: Http, private orderbyPipe: OrderbyPipe, public storage: Storage,private events:Events) {

    this.profileForm = this.formBuilder.group({
      name: ['', Validators.compose([Validators.required, Validators.minLength(3)])],
      mobile: ['', Validators.compose([Validators.required, this.myservice.checkLimit(10000000, 999999999999999)])],
      dial_code: ['+91', Validators.required],
      email: ['', Validators.compose([Validators.required, Validators.pattern("[a-zA-Z0-9.-_]{1,}@[a-zA-Z.-]{2,}[.]{1}[a-zA-Z]{2,}")])],
      password: ['', Validators.compose([Validators.minLength(6)])],//, 
      new: [''],//Validators.compose([ Validators.minLength(6)])
      confirm: [''],// Validators.compose([]), this.MatchPassword.bind(this)
      image:[''],
      secret_key: ['My_key']
    })

    this.http.get('dial-codes.json')
      .subscribe(response => {
        this.codes = response.json().dialCodes
        this.codes = this.orderbyPipe.transform(this.codes, 'dialCode');
      })
  }

  ionViewDidEnter(){
    this.storage.get('user_data').then(data=>{
      if(data){
        this.local = data
        this.profileForm.controls['name'].setValue(this.local.name)
        this.profileForm.controls['email'].setValue(this.local.email)
        this.profileForm.controls['dial_code'].setValue(this.local.dial_code)
        this.profileForm.controls['mobile'].setValue(this.local.mobile)
        this.profileForm.controls['image'].setValue(this.local.image)
        // this.myservice.load_post(this.local.id,'get_userProfile').subscribe(response=>{
        //   if(response.status == 'success'){

        //   }
        // })
      }
    })
  }

  update(){
    if(this.profileForm.value.password.length>0){
      this.profileForm.controls["new"].setValidators([Validators.minLength(6), Validators.required]);
      this.profileForm.controls["confirm"].setValidators([Validators.required]), this.MatchPassword.bind(this);
      this.profileForm.controls["confirm"].setAsyncValidators(this.MatchPassword.bind(this))
    }
    if(this.profileForm.valid){
      this.myservice.show_loader()
      this.formdata.append('data', JSON.stringify(this.profileForm.value));
      this.formdata.append('id', JSON.stringify(this.local.id));
      this.myservice.fileUpload(this.formdata,'update_user').subscribe(response=>{
        if(response.status=='success'){
          this.local = response.data
          var This = this
          setTimeout(() => {
          This.myservice.hide_loader()
            This.events.publish('user:profile', This.local);
          }, 500);
        }
        else{
          this.myservice.hide_loader()
          this.myservice.show_alert('',response.message)
        }
      })
    }
  }

  fileChange(event) {
    let fileList: FileList = event.target.files;
    if (fileList.length > 0) {

      var reader = new FileReader();

      reader.onload = (event: any) => {
        this.profileForm.controls['image'].setValue(event.target.result)
      }

      reader.readAsDataURL(event.target.files[0]);

      let file = fileList[0];
      var ext = (file.name).split(".").pop();
      if (ext == 'jpg' || ext == 'jpeg' || ext == 'png') {
        this.formdata.append('image', file, file.name);
        this.image = true;
      }
      else {
          this.myservice.show_alert("Error","Please choose an image file")
      }
    }
  }

  MatchPassword(val) {
    return new Promise(resolve => {
      if (val.value == this.profileForm.value.new) {
        resolve(null);
      }
      else {
        resolve({ 'match': false });
      }
    })
  }

}
