import { Component, ViewChild, ElementRef } from '@angular/core';
import { IonicPage, NavController, NavParams,Events } from 'ionic-angular';
import { Validators, FormBuilder, FormGroup } from "@angular/forms";
import { CommonProvider } from '../../providers/common/common';
import { Storage } from '@ionic/storage';
import  { user } from '../../providers/model/model';

import {TranslateService} from '@ngx-translate/core';
import { SubjectService } from '../../providers/subject.service';
import { WebService_lang } from '../../providers/web.service';
import * as $ from 'jquery';


/**
 * Generated class for the SignupPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-signup',
  templateUrl: 'signup.html',
})
export class SignupPage {
  @ViewChild('language') language: ElementRef;
  lang =  'en';
  signupForm: FormGroup;
  post_data:user;
  error:boolean = false;
  response_msg:string;
  success:boolean = false;
  device_id:any;

  constructor(
    public translate: TranslateService,
    public subjectService: SubjectService,
    public service_lang: WebService_lang, 
  	public navCtrl: NavController, 
  	public navParams: NavParams, 
  	public service: CommonProvider,
  	public formBuilder: FormBuilder, 
    public storage: Storage,
    public events: Events
  	) {

    this.signupForm = this.formBuilder.group({
      phone_no: ['', Validators.compose([Validators.required, this.service.checkLimit(10000000, 999999999999999)])],
      email_id: ['', Validators.compose([Validators.required, Validators.pattern("[a-zA-Z0-9.-_]{1,}@[a-zA-Z.-]{2,}[.]{1}[a-zA-Z]{2,}")])],
      password: ['', Validators.compose([Validators.required, Validators.minLength(6)])],
      confirm: ['', Validators.compose([Validators.required]), this.MatchPassword.bind(this)],
      terms: [null, Validators.compose([Validators.required, Validators.pattern('true')])],
      username:['', Validators.compose([Validators.required])],
      device_id:['']
    })
    this.device_id = '';
    this.subjectService.getLangData().subscribe(langData => {
      console.log(langData);
      this.lang = this.service_lang.getLocalStorageItem('lang');
      console.log(this.lang);
      if (this.lang) {
        translate.setDefaultLang(this.lang);
        translate.use(this.lang);
      }
    });

    
    const lang  = this.service_lang.getLocalStorageItem('lang');
    console.log(lang);

    if(lang !== undefined){
      this.lang = lang;
    }

    if(this.lang === 'ru') {
      $('body').addClass('ru');
    } else {
      $('body').removeClass('ru');
    }

   // this.lang = 'en';

    translate.setDefaultLang(this.lang);

    // the lang to use, if the lang isn't available, it will use the current loader to get them

    translate.use(this.lang);
  }

  ionViewDidLoad() {
    this.storage.get('get_deviceId').then(data => {
      console.log(data);
      if(data)
        this.device_id = data.userId;
    })
    console.log('ionViewDidLoad SignupPage');
  }

  register(){
    console.log(this.signupForm.value);
    this.service.show_loader();
    this.signupForm.controls['device_id'].setValue(this.device_id);
    this.post_data = { email_id:this.signupForm.value['email_id'],password:this.signupForm.value['password'],username:this.signupForm.value['username'],phone_no:this.signupForm.value['phone_no'],profile_pic:'assets/images/logo.png', device_id:this.device_id};  
    this.service.post_data('signUp',this.post_data).subscribe(data=>{
      console.log(data);
      this.response_msg = data.message;
      var token = token
      this.service.presentToast(this.response_msg);
      this.signupForm.reset();
      this.storage.set('token', data.token);
      this.storage.set('user_data', data.profile);
        this.events.publish('user:created', data.profile, Date.now());
        var This = this;
        this.service.hide_loader();
        setTimeout(() => {          
          This.navCtrl.setRoot('HomePage')
        }, 500);
      //this.storage.set('UserData', this.post_data);
      //this.navCtrl.push('LoginPage');
      //this.service.hide_loader();
    }, (err) => {
      var data = JSON.parse(err);
      console.log(data);
      this.response_msg = data['message'].join();
      this.service.presentToast(this.response_msg);
      this.service.hide_loader();
    })
  }

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

  signin(){
    this.navCtrl.push('LoginPage');
  }

}
