import { Component, OnInit, ElementRef, ViewChild } from '@angular/core';
import { Router,ActivatedRoute } from '@angular/router';
import { WebService } from '../../provider/web.service';
import { ImageStorage } from '../../../environments/server.config';
import { SubjectService } from '../../provider/subject.service';

@Component({
  selector: 'app-searchbar',
  templateUrl: './searchbar.component.html',
  styleUrls: ['./searchbar.component.scss']
})
export class SearchbarComponent implements OnInit {
  
  productArray: any;
  SingleProductData:any;
  imageServer: string;
  loginDetails:any;

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

  @ViewChild("productSearch") public productSearchRef: ElementRef;
  
  constructor(private router : Router, 
              private route: ActivatedRoute, 
              public webService: WebService,
              public subjectService : SubjectService) {
    this.productArray = true;
    this.imageServer  = ImageStorage;
  }

  ngOnInit() {
    this.checkUserLogin();
  }

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

  goToPage(path,data=null){
    this.router.navigate([path],{queryParams:  data});
    document.body.scrollTop  =  document.documentElement.scrollTop  =  0;
  }

  productSearchfun(product){
    if(product == ''){
      this.productArray = false;
      return;
    }
    this.webService.post_data('productSearch',{"key":product}).subscribe(response => {
      if(response.status == 'success'){
        this.productArray = response.data;
      } else {
        this.productArray = false;
      }
    });
  }

  productSearchFunClick(key){
      this.productArray = false;
      this.goToPage('productlist',{"key":key});
  }

    clickProduct(product_id){
      this.productArray = false;
      this.productSearchRef.nativeElement.value = ''; 
      this.goToPage('productdetails',{"product_id":product_id});
    }
}
