import { Component, OnInit, Inject, Injectable }      from '@angular/core'
import { Params, ActivatedRoute }                     from '@angular/router'
import { Location, isPlatformBrowser }                from '@angular/common'

import { DOCUMENT }                                   from '@angular/platform-browser'


import { SearchService }                              from '../../services/svc.search'
import { AppHelper }								  from '@k-settings/app-helper'

@Component({
	moduleId: module.id+'',
	selector: 'search-results',
	templateUrl: './tpl.results.pug',
	styleUrls: ['./sty.results.scss']
})
export class SearchResultsComponent implements OnInit {

	// Variables ----
	parameters: any;
	result: any;
	location: Object;
	searchterm: string;
	showAnchors: boolean = false
	appHelper = AppHelper
	productList = 'list'

	constructor(
		@Inject(DOCUMENT) private document: any,
		private _route: ActivatedRoute,
		private _searchService: SearchService,
		private _location: Location
	) {
		this._searchService.result$.subscribe((result) => {
			this.result = result
		})
		this._searchService.searchTerm$.subscribe((result) => {
			this.searchterm = result
		})
	}



	// Lifecycle Hooks ----
	ngOnInit() { 


		if(isPlatformBrowser) {
			this.showAnchors = true
		}


		// If on search route use `:needle` param for search
		this._route.params.subscribe((params: any) => {

			if(!!params.needle) {
				this.parameters = params.needle
				this.searchFor(params.needle)
			}
			
		})
	}



	// Functions ----

	/**
	 * Initiates a call to service to get results and update observable.
	 * Also changes the current route to reflect `needle` if on search route.
	 * 
	 * @param needle 
	 */
	searchFor(needle: string) {
		if(!!this.parameters && needle != this.parameters) {
			this._location.go('/search/'+needle)
		}
		this._searchService.getSearchResults(needle)
	}


	/**
	 * Close overlay and menu
	 */
	close() {
		this._searchService.closeAll()
	}


	scrollDisplay(title: string) {
		this.document.getElementById(title).scrollIntoView({block: "end", behavior: "smooth"})
	}
}