
// Core imports
import { Component, OnInit, Input } from '@angular/core'
import { Subject } from 'rxjs';
import { MatTableDataSource } from '@angular/material';

// Core Services


// Module Services


/**
 * @name KpiTableComponent
 * @description *watdo?*
 * @author *whodis?*
 * @since *wendis?*
 * @extends
 */
@Component({
    moduleId: module.id+ '',
    selector: 'search-orders-kpi-table',
    templateUrl: './template/t--kpi-table.pug',
    styleUrls: ['sty.kpi-table.scss']
})

export class KpiTableComponent {

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

    itemsContainer = {}
    dataSource = new MatTableDataSource<Element>()
    columnsToDisplay = ['kpi_name','qty', 'billed', 'discount_total', 'discountPercentage', 'averageBasketSize', 'hitRate']

    dataSourceSource = new Subject
    $dataSource = this.dataSourceSource.asObservable()

    constructor( ) {
        
        this.$dataSource.subscribe((result: any) => {

            this.dataSource.data = result
        })
    }


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

        if(!!this.orders) {

            this.itemsContainer = {} // Reset itemsContainer
            this.calculateKPI()
        }
    }


    // ---- Functions ---- \\
    generateItemContainer() {

        for(let order of this.orders) {

            if(!this.itemsContainer[order.type]) {
                this.itemsContainer[order.type] = {
                    kpi_name: order.type,
                    qty: 0,
                    billed: 0,
                    discount_total: 0,
                    discountPercentage: 0,
                    averageBasketSize: 0,
                    hitRate: (order.type == 'order' ? 0 : '-')
                }
            }
        }

    }


    // calculateKPIv2() {

    //     for(let order of this.orders) {

    //         this.createOrderLine(order).then((response: any) => {
    //             this.itemsContainer[order.type].qty += 1
    //             this.itemsContainer[order.type].billed += response.price
    //             this.itemsContainer[order.type].discount_total += response.discount_total
    //         })

    //         this.itemsContainer[order.type].averageBasketSize = this.itemsContainer[order.type].billed / this.itemsContainer[order.type].qty
    //         this.itemsContainer[order.type].discountPercentage = (((this.itemsContainer[order.type].discount_total / (this.itemsContainer[order.type].billed + this.itemsContainer[order.type].discount_total)) * 100) > 0 ) ? ((this.itemsContainer[order.type].discount_total / (this.itemsContainer[order.type].billed + this.itemsContainer[order.type].discount_total)) * 100).toFixed(2) + '%' : '-'

    //         if(order.type == 'order')
    //             this.itemsContainer[order.type].hitRate = ((this.itemsContainer[order.type].qty / (this.itemsContainer[order.type].qty + this.itemsContainer['basketItems'].qty)) * 100) ? ((this.itemsContainer[order.type].qty / (this.itemsContainer[order.type].qty + this.itemsContainer['basketItems'].qty)) * 100).toFixed(2) + '%' : '-'
    //     }

    //     this.dataSourceSource.next(Array.from(this.itemsContainer))
    // }

    /**
     * Calculates the KPIs based on specs, and outputs it into the form
     */
    calculateKPI() {

        let basketItems: any = {
            kpi_name: 'basket',
            qty: 0,
            billed: 0,
            discount_total: 0,
            discountPercentage: 0,
            averageBasketSize: 0,
            hitRate: '-'
        }

        let orderItems: any = {
            kpi_name: 'orders',
            qty: 0,
            billed: 0,
            discount_total: 0,
            discountPercentage: 0,
            averageBasketSize: 0,
            hitRate: 0
        }

        let autoBasketItems: any = {
            kpi_name: 'autoBaskets',
            qty: 0,
            billed: 0,
            discount_total: 0,
            discountPercentage: 0,
            averageBasketSize: 0,
            hitRate: '-'
        }

        new Promise((resolve) => {

            if(!!this.orders) {

                let index = 0

                for(let order of this.orders) {

                    console.log('Order Type:', order.type)

                    switch(order.type) {
                        case 'order':
                            this.createOrderLine(order).then((response: any) => {
                                orderItems.qty += 1
                                orderItems.billed += response.price
                                orderItems.discount_total += response.discount_total
                            })
                        break;
    
                        case 'basket':
    
                                this.createOrderLine(order).then((response: any) => {
                                    basketItems.qty += 1
                                    basketItems.billed += response.price
                                    basketItems.discount_total += response.discount_total
                                })
                        break;

                        case 'autoBaskets':
    
                                this.createOrderLine(order).then((response: any) => {
                                    autoBasketItems.qty += 1
                                    autoBasketItems.billed += response.price
                                    autoBasketItems.discount_total += response.discount_total
                                })
                        break;
                    }

                    index++

                    if(index >= this.orders.length) {
                        resolve()
                    }
                }
            }

        }).then(() => {

            // Calculate average price by dividing total billed with total quantity
            orderItems.averageBasketSize = orderItems.billed / orderItems.qty
            basketItems.averageBasketSize = basketItems.billed / basketItems.qty
            autoBasketItems.averageBasketSize = autoBasketItems.billed / autoBasketItems.qty
    
            // Find discount Percentage
            orderItems.discountPercentage = (((orderItems.discount_total / (orderItems.billed + orderItems.discount_total)) * 100) > 0 ) ? ((orderItems.discount_total / (orderItems.billed + orderItems.discount_total)) * 100).toFixed(2) + '%' : '-'
            basketItems.discountPercentage = ((basketItems.discount_total / (basketItems.billed + basketItems.discount_total)) * 100) ? ((basketItems.discount_total / (basketItems.billed + basketItems.discount_total)) * 100).toFixed(2) + '%' : '-'
            autoBasketItems.discountPercentage = ((autoBasketItems.discount_total / (autoBasketItems.billed + autoBasketItems.discount_total)) * 100) ? ((autoBasketItems.discount_total / (autoBasketItems.billed + autoBasketItems.discount_total)) * 100).toFixed(2) + '%' : '-'

            // Find order hit rate
            orderItems.hitRate = ((orderItems.qty / (orderItems.qty + basketItems.qty)) * 100) ? ((orderItems.qty / (orderItems.qty + basketItems.qty)) * 100).toFixed(2) + '%' : '-'
    
            this.dataSourceSource.next([basketItems, orderItems])
        })
    }


    /**
     * Creates an order line for easier math, isolates
     * the total value and the discount, then promisifies the result
     * 
     * @param order 
     */
    createOrderLine(order) {
        return new Promise((resolve) => {
            let element: any = {}

            element.price = order.prices.total
            element.discount_total = order.prices.discount

            resolve(element)
        })
    }
}