/**
 * Made by mkcomponent.sh
 * * Change to Fileheader info *
*/


import { Component, OnInit, Input, Inject, Injectable, ApplicationRef, PLATFORM_ID } from '@angular/core'
import { Location, isPlatformBrowser } from '@angular/common'
import { SearchOrderService }   from '../../services/svc.search-orders'
import { TranslatePipe }    from '@k-core/pipes/pipe.translate'
import { Observable, ReplaySubject } from 'rxjs'
import { tap, map, delay } from 'rxjs/operators'
import { of } from 'rxjs/observable/of'
import { fromEvent } from 'rxjs/observable/fromEvent'

interface Retailer {
    websiteId: number;
    name: string;
}

interface ISearchType {
    baskets: boolean;
    orders: boolean;
    autoBaskets: boolean;
}

interface IFilterPoint {
    value: string;
    label: string;
    selected: boolean;
    type: string;
}

@Component({
    moduleId: module.id+ '',
    selector: 'search-orders-search',
    templateUrl: './template/t--search.pug',
    styleUrls: ['sty.search.scss']
})

export class SearchComponent {

    // ---- Variables ---- \\
    @Input('user') user: any

    searchType: ISearchType = {
        baskets: false,
        orders: false,
        autoBaskets: false
    }
    disabled: boolean = false
    presetSearchTypeValue: string | string[] = ['baskets', 'orders']

    // Data
    busList: IFilterPoint[] = []
    bus: string = ''

    retailerList: Retailer[]
    retailer
    
    // Logic
    undisplayables = new Map

    orderSource: boolean = true
    kpiSource: boolean = true

    // Observables
    clear$ = new Observable((observer) => {
        observer.complete()
        observer.unsubscribe()
    })

    busListSource = new ReplaySubject<IFilterPoint[]>()
    busList$ = this.busListSource.asObservable()
    paymentStatuses$ = this._searchOrder.getPaymentStatuses()

    constructor(
        @Inject(PLATFORM_ID) private platformId: Object,
        private _searchOrder: SearchOrderService,
        private _translate: TranslatePipe
        
    ) {
        _searchOrder.getBus().subscribe((response) => {

            if(!!response.list) {

                // Set identifier on there, so we know which lookup needs to be done
                for(let listElement of response.list) {
                    listElement['type'] = 'bus'

                    if(!!listElement.value)
                        this.busList.push(listElement)
                }

                // this.busList = response.list
                // this.bus = this.busList[0].value
            } else {

                this.busList = []
            }

            this.busListSource.next(this.busList)
        })

        _searchOrder.getGroups().subscribe((response) => {
            
            if(!!response.groups) {

                for(let group of response.groups) {

                    let groupElement: IFilterPoint = {
                        value: group,
                        label: group,
                        selected: false,
                        type: 'group'

                    }

                    this.busList.push(groupElement)
                    this.busListSource.next(this.busList)
                }
            }
        })

        this.busList$.subscribe((resp) => {

            this.busList = resp
        })

    }




    // ---- Lifecycle hooks ---- \\
    ngOnInit() {

        for(let rights of this.user.search_hide) {
            this.undisplayables.set(rights, true)
        }

        this.presetSearchTypes()


        // Set retailers if any
        this.setRetailers(this.user.retailer_list)
    }


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

    /**
     * Checks preset, and sets is based on the value of `this.presetSearchTypeValue`
     */
    async presetSearchTypes() {

        if(this.presetSearchTypeValue == 'all') {
    
            // iterate searchType and set all values to true
            for(let key of Object.keys(this.searchType)) {
                this.searchType[key] = true
            }
        } else {

            if(this.presetSearchTypeValue instanceof Array) {

                // If Array is identified, iterate it, and set all its values to true
                for(let key of this.presetSearchTypeValue) {

                    this.searchType[key] = true
                }
            } else {

                // If it's not an array or 'all' expect string
                this.searchType[this.presetSearchTypeValue] = true
            }
        }
    }


    /**
     * Sets list of retailers if not empty
     * @param retailers 
     */
    setRetailers(retailers:Retailer[] = []) {
        if(!!retailers.length) {
            this.retailerList = retailers
        }
    }


    /** 
     * Clears the form and preset Radio button after clearing
     * 
     * @param form 
     */
    clear(form) {
        
        form.resetForm()

        setTimeout(() => {

            this.clear$.subscribe({
    
                error: e => {
                    console.error('Reset failed due to error: ' + e)
                },
                complete: () => {
    
                    this.presetSearchTypes()
                }
            })
        }, 100)
    }


    /**
     * Submits the form, checks if any values are set, and give a confirmation warning if they're not
     * 
     * @param form 
     */
    submit(form) {
        
        new Observable((observer) => {

            let searchType = []
    
            for(let key of Object.keys(this.searchType)) {
                if(this.searchType[key])
                    searchType.push(key)
            }
    
            form.value.searchTypes = searchType

            observer.next(form.value)
            observer.complete()

        }).pipe(
            map((form: any) => {

                let busField = 'bus'

                if(form[busField]) {

                    let selectedBus = this.busList.find((list) => {
                        return list.label == form[busField]
                    })
            
                    if(selectedBus.type == 'group') {

                        delete form[busField] 
                        form['group'] = selectedBus.label
                    }
                }

                return form
            })

        ).subscribe({
            next: (form) => {

                this.disabled = true
                this._searchOrder.getOrders(form).then(() => {
                    this.disabled = false
                })
            }
        })






        // if() {

        //     if(confirm(this._translate.transform('Ingen søgekriterier sat, det kan tage lang tid før du får nogle resultater'))) {
        //         this.disabled = true
        //         this._searchOrder.getOrders(form.value).then(() => {
        //             this.disabled = false
        //         })
        //     } 

        // } else {


        // }
    }
}