import { Component, OnInit, HostListener, ElementRef, ViewChild } from '@angular/core';
import { Router,ActivatedRoute } from '@angular/router';
import { FormGroup, FormControl, Validators, ValidationErrors } from '@angular/forms';
import { ValidationService } from './../provider/validation.service';
import { WebService } from './../provider/web.service';
import { SubjectService } from './../provider/subject.service';
import { ImageStorage } from '../../environments/server.config';

declare var $;
declare const window: any;

@Component({
  selector: 'app-navbar',
  templateUrl: './navbar.component.html',
  styleUrls: ['./navbar.component.scss']
})
export class NavbarComponent implements OnInit {

  data              : any;
  loader            : boolean;
  imageServer       : any;
  loginDetails      : any;
  loginResponse     : any;
  forgotResponse    : any;
  signupResponse    : any;
  spSignupResponse    : any;
  loginSubmitClick  : boolean;
  forgotSubmitClick : boolean;
  signupSubmitClick : boolean;
  spSignupSubmitClick : boolean;
  
  constructor (
    private router        : Router, 
    private route         : ActivatedRoute,
    public errorMsg       : ValidationService,
    public webService     : WebService,
    public subjectService : SubjectService) {
      this.imageServer        = ImageStorage;
      this.loginDetails       = false;
      this.loginSubmitClick   = false;
      this.forgotSubmitClick  = false;
      this.signupSubmitClick  = false;
      this.spSignupSubmitClick  = false;
  }

  loginForm;
  forgotForm;
  signupForm;
  autospsignupForm;
  @ViewChild('loginModal') loginModal: ElementRef;
  @ViewChild('signupModal') signupModal: ElementRef;
  @ViewChild('spModal') spModal: ElementRef;

  public scrollbarOptions = { axis: 'y', theme: 'minimal-dark' };

  ngOnInit() {
    this.subjectService.getLoginData().subscribe(loginData => {
      this.loginDetails = JSON.parse(this.webService.getLocalStorageItem('userData'));
    });

    this.loginForm = new FormGroup({
      email: new FormControl('', [Validators.required, Validators.maxLength(50), Validators.pattern('^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$')]),
      password: new FormControl('', [Validators.required, Validators.maxLength(16), Validators.minLength(6)])
    });
    
    this.forgotForm = new FormGroup({
      email: new FormControl('', [Validators.required, Validators.maxLength(50), Validators.pattern('^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$')])
    });

    this.signupForm = new FormGroup({
      email: new FormControl('', [Validators.required, Validators.maxLength(50), Validators.pattern('^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$')]),
      password: new FormControl('', [Validators.required, Validators.maxLength(16), Validators.minLength(6)]),

      phone: new FormControl('', [Validators.pattern("^[0-9\ ( ) + , - ]+$")]),
      promocode: new FormControl('', [Validators.pattern("^[a-zA-Z0-9\ _ - ]+$")]),

      last_name: new FormControl('', [Validators.required, Validators.pattern("^[a-zA-Z\ _ - ' \/]+$")]),
      first_name: new FormControl('', [Validators.required, Validators.pattern("^[a-zA-Z\ _ - ' \/]+$")])
    });

    this.autospsignupForm = new FormGroup({
      email: new FormControl('', [Validators.required, Validators.maxLength(50), Validators.pattern('^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$')]),
      phone: new FormControl('', [Validators.required, Validators.pattern("^[0-9\ ( ) + , - ]+$")]),
      password: new FormControl('', [Validators.required, Validators.maxLength(16), Validators.minLength(6)]),
      last_name: new FormControl('', [Validators.required, Validators.pattern("^[a-zA-Z\ _ - ' \/]+$")]),
      first_name: new FormControl('', [Validators.required, Validators.pattern("^[a-zA-Z\ _ - ' \/]+$")])
    });
  }
  
  loginSubmit(data) {
    if(this.loginForm.invalid){
      return false;
    }
    const This = this;
    this.loader = true;
    let funcName = 'customer_login';
    this.webService.post_data(funcName, data).subscribe(response => {
      this.loader = false;
      if ( response.status == '1') {
        this.webService.setLocalStorageItem('userData', JSON.stringify(response.data));
        this.subjectService.sendLoginData('logged_in');
        this.loginModal.nativeElement.click();
      } else {
        response.status = 'error';
        response.message = (response.message == '')?this.errorMsg.errorList.req_failure:response.message; 
        this.loginResponse = response;
      }
    },error => {
      this.loginResponse = {'status':'error','message':this.errorMsg.errorList.req_failure};
    },() => {
      setTimeout( function() {
        This.loginResponse = false;
      }, 2000)
    });
  }

  forgotSubmit(data){
    if(this.forgotForm.invalid){
      return false;
    }
    const This = this;
    this.loader = true;
    let funcName = 'customer_forgot_password';
    this.webService.post_data(funcName, data).subscribe(response => {
      this.loader = false;
      response.status = (response.status == '1')?'success':'error';
      response.message = (response.message == '')?this.errorMsg.errorList.req_failure:response.message;

      this.forgotResponse = response;
    },error => {
      this.forgotResponse = {'status':'error','message':this.errorMsg.errorList.req_failure};
    },() => {
      setTimeout( function() {
        This.forgotResponse = false;
      }, 2000)
    });
  }

  signupSubmit(data){
    if(this.signupForm.invalid){
      return false;
    }
    const This = this;
    this.loader = true;
    let funcName = 'customer_registration';
    this.webService.post_data(funcName, data).subscribe(response => {
      this.loader = false;
      if ( response.status == '1') {
        this.webService.setLocalStorageItem('userData', JSON.stringify(response.data));
        this.subjectService.sendLoginData('logged_in');

        this.signupModal.nativeElement.click();
      } else {
        response.status = 'error';
        response.message = (response.message == '')?this.errorMsg.errorList.req_failure:response.message;

        this.signupResponse = response;
      }
    },error => {
      this.signupResponse = {'status':'error','message':this.errorMsg.errorList.req_failure};
    },() => {
      setTimeout( function() {
        This.signupResponse = false;
      }, 2000)
    });
  }

  autospsignupSubmit(data){
    if(this.autospsignupForm.invalid){
      return false;
    }
    const This = this;
    this.loader = true;
    let funcName = 'service_provider_registration';
    this.webService.post_data(funcName,data).subscribe(response => {
      this.loader = false;
      if(response.status == '1'){
        response.status = 'success';
        response.message = 'Your Account has been created, Whenever it Activates will inform you.';
        this.spSignupResponse = response;

        setTimeout( function() {
          This.spSignupResponse = false;
          This.spModal.nativeElement.click();
          This.resetForm();
        }, 3000);
      }else{
        response.status = 'error';
        response.message = (response.message == '')?this.errorMsg.errorList.req_failure:response.message;

        this.spSignupResponse = response;
        setTimeout( function() {
          This.spSignupResponse = false;
        }, 3000);
      }
    },error => {
      this.spSignupResponse = {'status':'error','message':this.errorMsg.errorList.req_failure};
      setTimeout( function() {
        This.spSignupResponse = false;
      }, 3000);
    });
  }

  resetForm(){
    //Login Form
    this.loginForm.reset();
    this.loginResponse = false;
    this.loginSubmitClick = false;
    
    //Forgot Form
    this.forgotForm.reset();
    this.forgotResponse = false;
    this.forgotSubmitClick = false;
    
    //SignUP Form 
    this.signupForm.reset();
    this.signupResponse = false;
    this.signupSubmitClick = false;

    //Service provider Form
    this.autospsignupForm.reset();
    this.spSignupResponse = false;
    this.spSignupSubmitClick = false;
  }

  //Design
  @HostListener('window:scroll', [])

  onWindowScroll() {
    const number = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
    $(window).scroll(function() {
      var sticky = $('.navbar'),
          scroll = $(window).scrollTop();
      if (scroll > 1) sticky.addClass('scrolled_navbar');
      else sticky.removeClass('scrolled_navbar');
    });
  }
  goToPage(path,data=null){
    this.router.navigateByUrl(path,{queryParams:data});
    document.body.scrollTop = document.documentElement.scrollTop = 0;
  }

  logout() {
    const userData = this.webService.getLocalStorageItem('userData');
    this.webService.removeLocalStorageItem(userData);
    this.subjectService.sendLoginData(false);
    this.router.navigate(['../index']);
  }

}
