// Core imports
import { Component, Inject, PLATFORM_ID } from '@angular/core';
import { SendCartFactory } from '../../services/fac.send-cart';

// Services
import { SendCartService } from '../../services/svc.send-cart';
import { tap } from 'rxjs/operators'
import { of } from 'rxjs/observable/of';
/**
 * @name BusblockComponent
 * @description Creates a block for displaying "Bus Selection" with a dropdown and an input field
 * @author Kasper Hansen
 * @since 07-01-2019
 * ------------------------------
 * @author Kasper Hansen
 * @since 27-09-2019
 * @changelog Modified a promise into an observable, and trying to catch issues where BusId is `null` on the sessionStore
 */ 
@Component({
    moduleId: module.id+ '',
    selector: 'send-cart-busblock',
    templateUrl: './template/t--busblock.pug',
    styleUrls: ['sty.busblock.scss']
})

export class BusblockComponent {

    // ---- Variables ---- \\
    busses: any
    timeout: any
    id: string
    salesRep: boolean
    content: string = ''

    _session: any
    private _busIdSessionName = 'busId'

    // Observables
    /**
     * Observer to get the sessionStore, closes itself when it has gotten result
     */
    // private _basketObserver: Observable


    constructor(
        @Inject(PLATFORM_ID) private _platformId,
        private _sendCart: SendCartService,
        private _factory: SendCartFactory
    ) { }

    // ---- Lifecycle hooks ---- \\
    ngOnInit() {
        let currentBus: any = undefined

        this._factory.getBusIds().then((response: any) => {
            this.busses = response.list
            this.salesRep = response.showSalesRep


            // Subscriptions
            of(this._sendCart.sessionStore('get')).pipe(
                // tap((source) => {
                    
                //     currentBus = this.busses.find(element => {
                //         if(element.selected == true) {

                //             console.log(element)

                //             return element && element.value ? element.value : ''
                //         }
                //     })
                // }),

                // tap((response) => {
                //     if(!response[this._busIdSessionName]) {
                //         throw new Error('busIdSessionName does not exist')
                //     }
                // }),
                // tap((response) => {
                //     if(!response[this._busIdSessionName].currentBus) {
                //         throw new Error(`BusId not set, coming in as '${response[this._busIdSessionName].currentBus}', should be '${currentBus ? currentBus.value : ''}'`)
                //     }
                // })

            ).subscribe({

                next: (response) => {

                    
                    this.busses.find(element => {
                        if(element.selected = true)
                        element.selected = false
                        
                        if(element.value == response[this._busIdSessionName].currentBus)
                        element.selected = true
                    }) 
                    
                    if(response[this._busIdSessionName].content != 'undefined')
                    this.content = response[this._busIdSessionName].content
                    
                    this._sendCart.setBusBlockContent(this.id, this.content)
                    this._session = response
                    
                    this.changeBusId(response[this._busIdSessionName].currentBus)
                },
                error: (e: string) => {
                    console.warn(e)
                    this.changeBusId(currentBus)
                }
            })
        }) 
    }


    // ---- Functions ---- \\

    /**
     * Changes the bus Id based on what value is selected.
     * If `isEvent` is true, it will read from srcElement, else it will read directly
     * from `event`
     * 
     * @param {object | string} event $event | string
     * @param {boolean} isEvent true | false
     */
    changeBusId(event, isEvent = false) {
        if(isEvent)
            this.id = event.srcElement.value
        else {
            if(typeof event == 'object') {

                this.id = event.value
            } else {

                this.id = event
            }
        }

        let busElement = {
            currentBus: this.id,
            content: this.content
        }

        // Only update the cookie on event
        // if(isEvent)
        this._sendCart.sessionStore('set', this._busIdSessionName, busElement)

        this._sendCart.setBusBlockContent(this.id, this.content)
    }


    /**
     * Exposes the input field once changes, mainly handshaking value to `sessionStore` and `cart`
     * it does however, introduce a small delay (0.5 seconds) before exposing, to ensure it won't expose mid typing
     * 
     * @param event 
     */
    changeBusIdDescription(event) {

        let busElement = {
            currentBus: this.id,
            content: event.srcElement.value
        }

        this._sendCart.sessionStore('set', this._busIdSessionName, busElement)

        if(!!this.timeout)
            clearTimeout(this.timeout)

        this.timeout = setTimeout(() => {
            this.content = event.srcElement.value


            this._sendCart.setBusBlockContent(this.id, this.content)
        }, 500)
    }
}
