// NG Imports
import { Injectable } from '@angular/core'
import { HttpClient } from '@angular/common/http'
import { map } from 'rxjs/operators'
// Libraries
import { Observable, Subject } from 'rxjs'

// Settings
import { is_local } from '@k-settings/app-setup'

// Services
import { HelperService }    from '@k-services/svc.helper'
import { CookieService } from 'ng2-cookies'

// dummy data
import { dummyOrders } from './dummy-orders'
import { CheckFactory } from '@k-services/factories/fac.check'

interface PaymentRequest {
	"status": string,
	"data": {
	"list": PaymentList[]
	},
	"code": number
}

interface PaymentList {
    "value": string,
    "label": string
}
@Injectable()
export class SearchOrderService {
    
    ordersSource = new Subject<any>()
    orders$ = this.ordersSource.asObservable()

    searchOptionsSource = new Subject<any>()
    searchOptions$ = this.searchOptionsSource.asObservable()

    committedValues

    // Debugging
    is_local: boolean = is_local


    constructor(
        private _http: HttpClient,
        private _helper: HelperService,
        private _cookie: CookieService,
        private _checkLogin: CheckFactory
    ) {
    }

    // Variables ----
	api = `${this._helper.server}feed/get`
    ordersApi = this.api + '/order-search'


    /**
     * Gets orders as a POST request
     * 
     * @param values 
     */
    getOrders(values) {

        this.searchOptionsSource.next(values)

        console.log('getOrders', values)

        // Exclude this if testing locally
        if(!this.is_local) {
            this.committedValues = values
        }

        let object = {
            storeId: this._helper.storeId,
            websiteId: this._helper.websiteId,
            key: this._helper.apiKey,
            noCache: true,
        }

        for(let key of Object.keys(values)) {
            if(!!values[key])
                object[key] = values[key]
        }


        let promise

        // Local
        if(this.is_local) {
            console.warn('is local, returning dummy data')

            promise =  new Promise((resolve) => {
                resolve(true)
            }).then(() => {
                console.log('setting dummy data:', dummyOrders.data.orders)
                let orders = dummyOrders.data.orders
    
                this.ordersSource.next(orders)
                return orders
    
            })
        }

        // Not local
        else {
            promise = this._http.post(this.ordersApi, object).toPromise().then((response: any) => {
                if(response.status == 'error') throw response
                else {
                    this.ordersSource.next(response.data.orders)
                    return response.data.orders
                }
    
            }).catch((err) => {
                if(err.data.message) {
                    console.error(err.data.message)
                }
                else if(err.data.errorMessage){
                    console.error(err.data.errorMessage)
                }
            })
        }

        return promise
    }



	public getPaymentStatuses(): Observable<PaymentList[]> {
		return this._http.get<PaymentRequest>(`${this._helper.server}/feed/get/nav-status-list?key=${this._helper.apiKey}&storeId=${this._helper.storeId}&websiteId=${this._helper.websiteId}`)
			.pipe(
				map((response) => {
					return response.data.list
				})
			)
	}

    /**
     * getter for user
     * TODO: Describe better, if it works.
     */
    get user() {
        return this._checkLogin.checkLogin(this._cookie.get('kakesession')).toPromise().then((response) => {

            return response
        })
    }

    /**
     * Removes Order from system
     * TODO: get API call that actually removes the order
     * 
     * @param id 
     */
    removeOrder(id) {

        let object = {
            storeId: this._helper.storeId,
            websiteId: this._helper.websiteId,
            key: this._helper.apiKey,
            noCache: true,
            remove: true,
            id: id
        }

        return this._http.post(this.ordersApi, object).toPromise()
    }


    /**
     * assigns `list` as the new `order$`
     * 
     * @param list 
     */
    setOrderList(list) {
        this.ordersSource.next(list)
    }


    /**
     * Gets curtain bus list from API
     */
    getBus() {

        let object = {
            storeId: this._helper.storeId,
            websiteId: this._helper.websiteId,
            key: this._helper.apiKey,
            noCache: true,
        }

        return this._http.post(this.api + '/curtain-busses', object)
            .pipe(map((response: any) => {
                return response.data
            }))
    }

    getGroups() {
        let object = {
            storeId: this._helper.storeId,
            websiteId: this._helper.websiteId,
            key: this._helper.apiKey,
            noCache: true,
        }

        return this._http.post(this.api + '/bus-groups', object).pipe(map((response: any) => {
            return response.data
        }))
    }
}