import { Component, OnInit, ViewChild,EventEmitter } from '@angular/core';
import { SearchService } from './search.service';
import { Http, Response, Headers } from '@angular/http';
import { ActivatedRoute } from '@angular/router';
import { Item } from '../../ecm-model/product-model';

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { Observable } from 'rxjs/Observable';
import { HostUrlService } from '../../host-url.service';


@Component({
  selector: 'ecm-search-result',
  templateUrl: './ecm-search-result.component.html',
  styleUrls: ['./ecm-search-result.component.css']
})
export class EcmSearchResultComponent implements OnInit {
  
  searchResponse: any;
  items:Item[];
  value;
  start=0;
  numFound;
  pageCount;
  activePage;
  myCity;
  resultFound:boolean = true;
  serverError;
  sortType="rating desc";
  filterType="itemCode:[* TO *]";
  solrUrl= '/ecm/service/solr/local2do/';
  loading:boolean = true;
  
  color = 'primary';
  mode = 'indeterminate';
  spinnerValue = 50;
  hostUrl;
  @ViewChild('page') page;
  
  constructor(public hostUrlService : HostUrlService,private search_service: SearchService, private http:Http, private route:ActivatedRoute) {
       this.hostUrl=this.hostUrlService.hostUrl;
  }

  ngOnInit() {
       console.log( 'ECMSearch onInit hostUrl' , this.hostUrl);
   
   this.myCity = localStorage.getItem('mycity');
   if(this.myCity == null)
      this.myCity = undefined;
   console.log(this.myCity+'----------'); 
   this.route.params.subscribe( params => {
          this.loading = true;
          this.value = params['value'];
          this.activePage=1;
          window.scrollTo(0,0);
          this.start=0;
          if(!(this.value.indexOf('*') > -1))
          {
           this.fetchItems();                            
          } 
          else
          {
           this.items = undefined; 
           this.searchResponse = undefined;
           this.resultFound = false;
           this.numFound = 0;
           this.loading = false;
          } 
    }
   );
  }
  
  fetchItems(){
    var solrUrl= this.solrUrl+this.value+'/json/'+this.start+'/'+this.sortType+'/'+this.filterType; 
     
    this.http.get(solrUrl)
      .map(res => res.json())
      .subscribe(data => {
       this.searchResponse = data;     
       if(data.response)
        this.items = data.response.docs;
       this.serverError = false;
       if(this.items)       
         this.loading = false;    
      }, err => this.serverError = true); 
  }
  
  ngAfterContentChecked(){
   if(this.searchResponse)
   {
    if(this.searchResponse.response)
    {
     this.numFound=this.searchResponse.response.numFound;
    } 
    if(this.numFound==0)
    {
     this.resultFound = false;
    }
    else
    {
     this.resultFound = true;
    }
    
    this.pageCount=Math.ceil((this.numFound/10));
   }
  }
  
  
  loadNext(){       
  	if(!(this.activePage == this.pageCount))
  	{
  	  window.scrollTo(0,0);
  	  this.start+=10;
  	  this.activePage+=1;
  	  
  	  this.fetchItems();
    }
  }
  
  loadPrevious(){
  	if(!(this.activePage == 1))
  	{
  	 window.scrollTo(0,0);
  	 this.start-=10;
  	 this.activePage-=1;
  	      	    
     this.fetchItems();
    }
  }

  createPages(){
  	var pages: number[] = [];
  	for(var i = 1; i <= this.pageCount; i++){
     pages.push(i);
    }
    return pages;
  }
  
  goToPage(value){
    window.scrollTo(0,0);
  	this.start=((value+1)*10)-10;
  	this.activePage=value+1;
  	
  	if(this.numFound>(this.start))
  	{
     this.fetchItems();
    }  
  }
  
  sortBy(value){
    console.log(value);
  	if(value=='Rating')
  	 this.sortType='rating desc';
  	if(value=='Price: High to Low') 
  	 this.sortType='costRate desc';
  	if(value=='Price: Low to High')
  	 this.sortType='costRate asc';
  	
  	this.fetchItems();   	
  }
  
  private handleError (error: Response | any) {
    // In a real world app, we might use a remote logging infrastructure
    this.serverError = true;
    let errMsg: string;
    if (error instanceof Response) {
      const body = error.json() || '';
      const err = body.error || JSON.stringify(body);
      errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
      errMsg = error.message ? error.message : error.toString();
    }
    console.error('Service handleError:' + errMsg);
    return Observable.throw(errMsg);
  }
}
