// Core imports
import { Component, OnInit, Inject, PLATFORM_ID } from '@angular/core'
import { ActivatedRoute } from '@angular/router';
import { isPlatformBrowser } from '@angular/common'
import { trigger, state, style, transition, animate } from '@angular/animations'

import { AppHelper } from '@k-settings/app-helper'

// Services
import { HelperService } from '@k-services/svc.helper'
import { SendCartService } from '../../services/svc.send-cart'
import { SendCartFactory } from '../../services/fac.send-cart'
import { DiscountsService } from '@k-common/discount/services/svc.discounts'



import { IDiscount } from '@k-core/interfaces/send-cart';
import { LocalstorageService, SessionstorageService } from '@k-core/services/general/storage';

interface IMessage {
    state: string;
    message: string;
    class?: string;
}

/**
 * @name DiscountComponent
 * @description Generates discounts and exposes to price calculations based on inputs
 * @author Kasper Hansen
 * @since 07-01-2019
 */
@Component({
    moduleId: module.id+ '',
    selector: 'send-cart-discount',
    templateUrl: './template/t--discount.pug',
    styleUrls: ['sty.discount.scss'],
    animations: [
        trigger('message', [
            state('none', style({ opacity: 0, transform: 'scale(0)' })),
            state('success', style({ opacity: 1, transform: 'scale(1)' })),
            state('error', style({ opacity: 1, transform: 'scale(1)' })),

            transition('none => success', [
                animate('300ms ease-out', style({ transform: "scale(1.2)" })),
                animate('150ms ease-in')
            ]),

            transition('success => none', [
                animate('200ms ease-in', style({ transform: "scale(1.05)" })),
                animate('100ms ease-out')
            ]),

            transition('none => error', [
                animate('300ms ease-out', style({ transform: "scale(1.2)" })),
                animate('150ms ease-in')
            ]),

            transition('error => none', [
                animate('200ms ease-in', style({ transform: "scale(1.05)" })),
                animate('100ms ease-out')
            ])
        ])
    ]
})

export class DiscountComponent implements OnInit {

    // ---- Variables ---- \\
    open: boolean = false
    cart: any
    discountCalculationCart: any
    discountCode: any
    message: IMessage = {
        state: 'none',
        message: '',
        class: 'success'
    }
    constructor(
        @Inject(PLATFORM_ID) private _platformId,
        public localStorage: LocalstorageService,
        public sessionStorage: SessionstorageService,
        private _helper: HelperService,
        private _sendCart: SendCartService,
        private _factory: SendCartFactory,
        private _activatedRoute: ActivatedRoute,
        private _discounts: DiscountsService
    ) {

        _sendCart.cart$.subscribe((response) => {
            this.cart = response
        })

        _factory.couponMessage$.subscribe((response) => {
            this.message = response

            this.showMessage()
        })

        if(isPlatformBrowser(this._platformId)) {
            this._factory.coupons = new Map(JSON.parse(this.sessionStorage.getItem('kake-discounts')))

            for(let coupon of Array.from(this._factory.coupons.values())) {

                this._factory.addDiscount({value: coupon}, true).then((response) => {
                    this._sendCart.setDiscounts(response)
                })
                
            }
        }
    }


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

    }


    // ---- Functions ---- \\
    /**
     * Displays success message if possible, ellers error message
     */
    showMessage() {
        // 2.5 seconds * 1000 to turn into ms
        let time = (2.5 * 1000)

        if(this.message.state == 'success')
            this.message.class = 'success'
        else if(this.message.state == 'error')
            this.message.class = 'error'

        // Removes the message after `time`
        setTimeout(() => {
            this.message.state = 'none'
        }, time)
    }

    /**
     * toggles `open` to the `boolean` opposite of what it currently is
     */
    toggleOpen() {
        this.open = !this.open
    }


    /**
     * Adds the discount code to the `Quote`, then adds it to the cart
     * 
     * @param code 
     */
    addDiscounts(code) {

        this._factory.addDiscount(code).then((response) => {

            this._sendCart.setDiscounts(response)
        })
    }

    /**
     * Removes the discount code from the `Quote`, then removes it from cart
     * 
     * @public
     * @param code 
     */
    removeDiscount(code) {
        new Promise((resolve) => {

            resolve(JSON.parse(this.localStorage.getItem(AppHelper.basketIdentifier)))

        }).then((response) => {
            this.discountCalculationCart = response
            let newCode: string = undefined
    
            // Checks if the code is an `individual rabat`
            if(code.includes('-ir--')) {
                newCode = (!code.includes('DI_') ? code.replace('-ir--', '-ir--DI_') : code)
            } else {
                newCode = code
            }
            
            
            this._factory.removeDiscount(newCode).then((response) => {
                
                if(newCode.includes('-ir')) {
                    this._removeIndividualDiscount(newCode)
                } else {
                    this._sendCart.renderItems()
                }
            })
        })
    }


    /**
     * Removes individual discount code, and re-posts the cart to localStorage
     * 
     * @private internal tool
     * @param code 
     */
    private _removeIndividualDiscount(code) {

        let debug = false

        this._activatedRoute.queryParams.take(1).subscribe((param) => {
            if(!!param.debug && param.debug == 'discount') {
                debug = true
            }
        })


        this._discounts.clearMountDiscounts(code)



        if(isPlatformBrowser(this._platformId)) {

            new Promise((resolve) => {

                // Debugging
                if (debug) console.warn('_removeIndividualDiscount --- plain result', JSON.stringify(this.discountCalculationCart))
    
                // // finds the target in basket
                let modifiedCart = []

                // Generate an array of all elements, that doesn't have the code
                for(let product of this.discountCalculationCart) {

                    if(!product.id.includes(code.split('_')[code.split('_').length - 1])) {
                        modifiedCart.push(product)
                    }
                }


                // Debugging
                if (debug) console.warn('_removeIndividualDiscount --- cart after delete', JSON.stringify(modifiedCart))
                if (debug) console.warn('_removeIndividualDiscount --- filter_array cart: ', JSON.stringify(this._helper.filter_array(modifiedCart)))
    
                this.showMessage()
                    
                resolve(modifiedCart)

            }).then((cart) => {
                    
                this.localStorage.setItem(AppHelper.basketIdentifier, JSON.stringify(this._helper.filter_array(cart)))

                return cart

            }).then((cart) => {
                
                this._sendCart.renderItems()
            })
        }
    }


    /**
     * Will trim whitespace from the value of an input
     * 
     * @param event 
     */
    removeWhitespace(event, id: string, label: string) {
        let trimmedValue = event.target.value.trim()

        event.target.value = trimmedValue
    }
}