import { Component, ViewChild, ElementRef } from '@angular/core';
import { IonicPage, NavController, NavParams, Events } from 'ionic-angular';
import { Validators, FormGroup, FormBuilder } from '@angular/forms';
import { Storage } from '@ionic/storage';
import { CommonProvider } from '../../providers/common/common';
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 LoginPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-login',
  templateUrl: 'login.html',
})
export class LoginPage {
  @ViewChild('language') language: ElementRef;
  lang =  'en';
		local:user;
  		loginForm: FormGroup;
  		device_id: any;

  constructor(
    public translate: TranslateService,
    public subjectService: SubjectService,
    public service_lang: WebService_lang, 
  	public navCtrl: NavController, 
    public navParams: NavParams, 
    private formBuilder: FormBuilder, 
    private service: CommonProvider, 
    public storage: Storage,
    public events: Events,
  	) {
    console.log('called login');
    this.device_id = '';
    this.storage.get('get_deviceId').then(data => {
      console.log('sadasdasdasdasd');
      console.log(data);
      if(data){
        this.device_id = data.userId;
      }
    })

  	this.loginForm = this.formBuilder.group({
      username: ['', Validators.compose([Validators.required])],
      password: ['', Validators.compose([Validators.required, Validators.minLength(6)])],
      device_id:[this.device_id]
    })

    

    console.log("device:"+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 LoginPage');
  }

  login(){
  	this.service.show_loader();
   console.log("login_val", this.loginForm.value);
      var This = this;


      This.storage.get('get_deviceId').then(data => {
      console.log('sadasdasdasdasd');
      console.log(data);
      if(data){
        this.loginForm.controls['device_id'].setValue(data.userId);
        
        setTimeout(function(){
          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());
        
        This.service.hide_loader();
        setTimeout(() => {          
          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();
    })

        },500);        
      }
    })

    
 }

 signup(){
    this.navCtrl.push("SignupPage");
  }

  forgot(){
    this.navCtrl.push("ForgotPage");
  }

}
