
// Core imports
import { Component, OnInit } from '@angular/core'
import { GoogleApisService } from '@k-core/services/svc.googleApis'
import { Subscription } from 'rxjs'

// Core Services


// Module Services
import { SendCartService } from '../../services/svc.send-cart'

/**
 * @name MutualagreementComponent
 * @description *watdo?*
 * @author *whodis?*
 * @since *wendis?*
 * @extends
 */
@Component({
    moduleId: module.id+ '',
    selector: 'send-cart-mutual-agreement',
    templateUrl: './template/t--mutualAgreement.pug',
    styleUrls: ['sty.mutualAgreement.scss']
})

export class MutualAgreementComponent {

    // ---- Variables ---- \\

    timeout: any
    message: string = ''
    private _sessionKey = 'mutualAgreement'
    private _cart: any[] = []

    getCartTimeout: any
    pasus: any[]

    subscriptions = new Subscription()
    constructor(
        private _sendCart: SendCartService,
        private _googleApis: GoogleApisService,
    ) {

    }


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

        // Gets cart so it can be used for internal requests
        this.subscriptions.add(

            this._sendCart.cart$
                .subscribe({
                    next: (cart) => {
                        this._cart = cart.products
    
                        if(this.getCartTimeout) {
                            clearTimeout(this.getCartTimeout)
                        }

                        this.getCartTimeout = setTimeout(() => {

                            if(this._cart.length) {
                                console.log('get pasus', this._cart)
                                this.getPasus()
                            }
                            
                        }, 500)
                    }
                })
        )
    }


    ngOnDestroy() {
        this.subscriptions.unsubscribe()
    }
    // ---- Functions ---- \\

    
    /**
     * Gets Google Datasheet to provide PASUS
     */
    getPasus() {
        this.subscriptions.add(

            this._googleApis.getSheet('2PACX-1vS5lANXoKbac3wfae75LV94f6Ku9V4YCrqiMKWxPnOOR82-K80ceRPuwFHhPdtFGyRXAfikV4lGOlxN')
                .subscribe(async (response) => {
    
                    let entries = []
    
                    // iterates all entries, if their typeId is seperated with a |, then split them into their own entries, to ensure no duplicates
                    for await(let entry of response) {
                        if(entry.typeid.includes('|')) {
                            entry.typeid.split('|').forEach((key) => {
                                entries.push({typeid: key, pasus: entry.pasus, tekst: entry.tekst})
                            })
                        } else {
                            entries.push(entry)
                        }
                    }
    
                    // Filters PASUS based on products, if 1 entry exists, display it, afterwards remove duplicate PASUS entries
                    if(!this.pasus) {
    
                        this.pasus = entries
                            .filter((pasus) => {

                                // console.log('cart products', this._cart)

                                return this._cart.find((product) => {
    
                                    if('type_id' in product) {
    
                                        product.type_id = product.type_id === 'plato' ? 'SUNWAY_SUPER' : product.type_id
    
                                        return product.type_id == pasus.typeid
                                    }
    
                                    return product.data.find((data) => data.type_id == pasus.typeid)
                                })
                            })
                            .filter((el) => {
                                if(!this[el.pasus]) {
                                    this[el.pasus] = true
                                    return true
                                } else {
                                    return false
                                }
                            })
                    }
                })
        )

            // TODO: Rewrite as observable
            new Promise((resolve) => {
                resolve(this._sendCart.sessionStore('get'))

            }).then((response) => {

                if(!!response[this._sessionKey]) {
                    this.message = response[this._sessionKey]
                }
            })
    }

    /**
     * Sets a common and exposes it to `sessionStore` and `cart` after a 0.5 second delay
     * 
     * @param event 
     */
    setAgreement(event?) {

        if(!!event && 'srcElement' in event) {

            this.message = event.srcElement.value
        } else if(!!event) {
            this.message = event
        }

        this._sendCart.sessionStore('set', this._sessionKey, this.message)

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

        this.timeout = setTimeout(() => {
            this._sendCart.setMutualAgreement(this.message)
        }, 500)
    }


    /**
     * Runs when a checkbox changes state
     * 
     * @param event HTMLCheckboxEvent
     * @param pasus 
     */
    isChecked(event, pasus) {

        const _message: string = `${pasus.tekst}\n\n`

        if(event.checked) {

            this.message += _message
        } else {

            if(this.message.includes(`${pasus.tekst}\n\n`)) {

                this.message = this.message.replace(_message, '')
            }
        }

        // Sets the event actively
        this.setAgreement()
    }
}
