import { Component, ViewChild , ElementRef} from '@angular/core';
import { IonicPage, NavController, NavParams, Events, ViewController } 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';
declare var google;

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

@IonicPage()
@Component({
  selector: 'page-signupmodal',
  templateUrl: 'signupmodal.html',
})
export class SignupmodalPage {
  @ViewChild('language') language: ElementRef;
	lang =  'en';
	log_status:any;
	signupForm: FormGroup;
	post_data:user;
	error:boolean = false;
	response_msg:string;
	success:boolean = false;
	device_id:any;
	local:user;
  	loginForm: FormGroup;
  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,
    public viewCtrl: ViewController
    ) {
  	this.log_status = 0;
  	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.loginForm = this.formBuilder.group({
      username: ['', Validators.compose([Validators.required])],
      password: ['', Validators.compose([Validators.required, Validators.minLength(6)])],
      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() {
    console.log('ionViewDidLoad SignupmodalPage');
    this.storage.get('get_deviceId').then(data => {
      console.log(data);
      if(data)
        this.device_id = data.userId;
    })
  }

  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.viewCtrl.dismiss(data.profile);
          //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.log_status = 0;
  }

  login(){
  	this.service.show_loader();
   console.log(this.loginForm.value);
   this.loginForm.controls['device_id'].setValue(this.device_id);
    this.service.post_data('signIn',this.loginForm.value).subscribe(response=>{
      if (response.status == 'success'){
      	this.storage.set('token', response.token);
        this.storage.set('user_data', response.profile);
        this.events.publish('user:created', response.profile, Date.now());
        var This = this;
        this.service.hide_loader();
        setTimeout(() => {
          This.viewCtrl.dismiss(response.profile);
          //This.navCtrl.setRoot('HomePage')
        }, 500);
      }
      else{
      	this.service.hide_loader();
        this.service.presentToast("Invalid username and Password");
      }
    }, (err) => {
      var data = JSON.parse(err);
      console.log(data);
      this.service.presentToast(data['message']);
      this.service.hide_loader();
    })
 }

 signup(){
   this.log_status = 1;
  }
  forgot(){
    this.navCtrl.push("ForgotPage");
  }

}
