// TODO: Collection and Product service can be refactored into a single service 
// as they are similar

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

import 'rxjs/add/operator/toPromise';

// Types
import { CategoryType }     from '../types/category';
import { CategoriesType }   from '../types/categories';

// Helpers
import { HelperService }    from './svc.helper';
import { SharedService }    from './svc.shared';
import { map } from 'rxjs/operators';


@Injectable()
export class CategoryService {

    constructor(
        private _http: HttpClient, 
        private _helper: HelperService,
        private _shared: SharedService
    ) { }

    private key = this._helper.credentials;
    private api = this._helper.server+'feed/get';

    private multiCollection = this.api + '/cached-categories' + this.key;
    private singleCollection = this.api + '/category' + this.key;


    private handleError(error: any): Promise<any> {
        console.error('An error occurred', error); // for demo purposes only
        return Promise.reject(error.message || error);
    }

    // Gets all Categories
    getCategories(): Promise<CategoriesType[]> {
        return this._http.get(this.singleCollection)
            .toPromise()
            .then((response: any) => response.data as CategoryType[])
            .catch(this.handleError);
    }

    // Gets collection based on ID
    getCollection(id:string): Promise<CategoryType> {
        return this._http.get(this.singleCollection+'&id='+id+'&getProducts&extend')
            .toPromise()
            .then((response: any) => response.data.category as CategoryType)
            .catch(this.handleError);
    }
    // feed/get/category?key=4705e0978195177adfc47df648403317&name=Hovedkategori&getChildren&getProducts
    // Gets collection based on URLKey
    getCollectionByUrlKey(urlkey:string) {

        let options = {
            params: {
                key: this._helper.apiKey.toString(),
                storeId: this._helper.storeId.toString(),
                websiteId: this._helper.websiteId.toString(),
                getProducts: true.toString(),
                getChildren: true.toString(),
                extend: true.toString(),
                urlkey: urlkey
            }
        }

        return this._http.get(this._helper.server + '/feed/get/category', options)
            .pipe(
                map((response: any) => {
                    
                    console.log(response)
                    // Set shared Category
                    this._shared.setCollection([{name: response.data.category.name, urlkey: response.data.category.urlkey}]); 
                    return response.data.category as CategoryType
                })
            )
    }


    // /feed/get/category?key=85dad81baeb4be73d4348fbcfdaf8269&id=4&getProducts&excludedProducts=sku:6074SGL&debug=1
    getLimitedCollection(id:number, collectionId: number): Promise<CategoryType> {

            return this._http.get(this.singleCollection+'&id='+collectionId+'&getProducts&excludeProducts='+id)
            .toPromise()
            .then((response: any) => response.data.category as CategoryType)
            .catch(this.handleError);
    }


    /**
     * gets quantity of a list of skus
     * /feed/get/stock?key=4705e0978195177adfc47df648403317&websiteId=4&storeId=8&sku=534506,559641,451071&noCache
     */
    getQuantity(ids: string[]) {
        let stringOfIds = ids.toString()

        return this._http.get(this.api + '/stock' + this.key + '&sku=' + stringOfIds + '&noCache')
            .pipe(
                map((response: any) => {
                    
                    return response.data.products
                })
            )
    }

}