import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { ValidationService } from './../../providers/validation.service';
import { SubjectService } from './../../providers/subject.service';
import { WebService } from './../../providers/web.service';
import * as $ from 'jquery';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})



export class LoginComponent implements OnInit {
  @ViewChild('focus1') focus1: ElementRef;
  @ViewChild('focus2') focus2: ElementRef;
  @ViewChild('focus3') focus3: ElementRef;
  @ViewChild('focus4') focus4: ElementRef;
  @ViewChild('focus5') focus5: ElementRef;
  @ViewChild('focus6') focus6: ElementRef;
  @ViewChild('language') language: ElementRef;
  error_msg: any[];
  lang =  'en';
  model: any;
  passwordErr: boolean;
  password: any;
  fname: any;
  loginSubmit: boolean;
  loginError: boolean;
  loginMsg: any;
  loginDetails: any;
  loader: boolean;
  val = 0;
  constructor(
    private router: Router,
    private route: ActivatedRoute,
    public vs: ValidationService,
    public service: WebService,
    public subjectService: SubjectService,
  ) {
    this.error_msg = this.vs.errorList[this.lang];
    console.log(this.error_msg);
    this.passwordErr = false;
    this.loginSubmit = false;
    this.loginError = false;
    this.loader = false;

    this.subjectService.getLoginData().subscribe(loginData => {
      this.loginDetails = JSON.parse(this.service.getLocalStorageItem('userData'));
      if (this.loginDetails) {
        if (this.loginDetails.user_type === 1) {
          this.router.navigate(['maker/home']);
        } else if (this.loginDetails.user_type === 2) {
          this.router.navigate(['forex']);
        } else if (this.loginDetails.user_type === 3) {
          this.router.navigate(['delivery']);
        } else {
        }
      }
    });
  }

  ngOnInit() {
    this.model = {'email_id': '', 'password': ''};
    // this.language.nativeElement.value = this.lang === 'ar' ? 1 : 0;
  }

  goToPage(path: any, data = null) {
    console.log(data);
    this.router.navigateByUrl(path, {queryParams: data});
    document.body.scrollTop = document.documentElement.scrollTop = 0;
  }

  processKeyUp(e: any, el: any) {
    console.log(e.keyCode);
    if ((e.keyCode >= 48 && e.keyCode <= 57) || (e.keyCode >= 96 && e.keyCode <= 105)) {
      el.focus();
    } else {
      if (e.keyCode !== 8) {
        e.target.value = '';
      }
    }
  }




  processBack (e: any, el: any) {
    console.log(e);
    if (e.keyCode === 8) {
      e.target.value = '';
      el.focus();
    }
  }

  loginClick() {
    this.loginSubmit = true;
    this.passwordErr = false;
    this.loginError = false;
    const password = [];
    password[0] = this.focus1.nativeElement.value;
    password[1] = this.focus2.nativeElement.value;
    password[2] = this.focus3.nativeElement.value;
    password[3] = this.focus4.nativeElement.value;
    password[4] = this.focus5.nativeElement.value;
    password[5] = this.focus6.nativeElement.value;

    const pass = password.join('');

    if (this.model.email_id === '') {
      if (pass === '') {
        this.passwordErr = true;
      }
      return false;
    }
    for (const i in password) {
      if (password[i] === '') {
        this.passwordErr = true;
        return false;
      }
    }

    this.loader = true;

    this.fname = 'admin_login';
    const post_data = {'email_id': this.model.email_id, 'password': pass};
      this.service.post_data(this.fname, post_data).subscribe(response => {
        this.loader = false;
        console.log(response);
        if (response.code === 1) {
          const responseData = response.responseResult;
          this.service.setLocalStorageItem('userData', JSON.stringify(response.responseResult));
          this.subjectService.sendLoginData('logged_in');
          if (responseData.user_type === 1) {
            this.router.navigate(['maker/home']);
          } else if (responseData.user_type === 2) {
            this.router.navigate(['forex']);
          } else if (responseData.user_type === 3) {
            this.router.navigate(['delivery']);
          } else if (responseData.user_type === 5) {
            this.router.navigate(['checker/home']);
          } else {
            this.loginError = true;
            this.loginMsg = this.vs.errorCode['ER42'];
          }
        } else {
          this.loginError = true;
          this.loginMsg = this.vs.errorCode[this.lang][response.errorCode];
          console.log(this.loginMsg);
        }
      }, (error) => {
        this.loginError = true;
        this.loginMsg = this.vs.errorCode[this.lang]['ER08'];
        console.log(this.loginMsg);
    });
  }

  changeLang(val: string) {
    if (val === '1') {
      $('body').addClass('ar');
      this.lang = 'ar';
      this.service.setLocalStorageItem('lang', 'ar');
    } else {
      $('body').removeClass('ar');
      this.lang = 'en';
      this.service.setLocalStorageItem('lang', 'en');
    }
    this.subjectService.changeLang(val);
  }

}
