import { Injectable } from '@angular/core'
import { HttpClient } from '@angular/common/http'
import { Subject } from 'rxjs/Subject'

import { HelperService } from '@k-services/svc.helper'
import { SharedService } from '../../../services/svc.shared'
import { MenuService }   from '@k-services/svc.menu'


@Injectable()
export class SearchService {
    
    // Vars

    // Observable String Source
    private stateSource = new Subject<boolean>()
    private resultSource = new Subject<Object>()
    private searchTermSource = new Subject<string>()
    
    // Observable String Stream
    state$ = this.stateSource.asObservable()
    result$ = this.resultSource.asObservable()
    searchTerm$ = this.searchTermSource.asObservable()
    state: boolean = false


    constructor(
        private _http: HttpClient,
        private _helper: HelperService,
        private _shared: SharedService,
        private _menuService: MenuService
    ) {
        this.state$.subscribe((result) => {
			this.state = result
		})
    }




    // Functions
    

    /**
     * Calls feed with `needle` and updates observable source
     * with the result.
     * 
     * @param needle 
     */
    getSearchResults(needle: string): void {

        this._http.get(this._helper.server + 'feed/get/search' + this._helper.credentials + '&search='+needle + '&target=products,categories&&extend')
            .toPromise()
            .then((response:any) => {
                // TODO: Errorhandling ?

                this.resultSource.next(response.data)
                this.searchTermSource.next(needle)
            })
    }




    
    /**
     * Toggle state value, defeaults to oposite of current
     * @param state 
     */    
    toggleSearchState(state?:boolean) {
        state = state ? state : !this.state
        this.stateSource.next(state)
    }


    /**
	 * Closes search overlay and menu
	 */
	closeAll() {
		this._menuService.toggleState(false)
		this.toggleSearchState(false)
	}
}