// Core imports
import { Component, OnInit } from '@angular/core'

// Services
import { SendCartService } from '../../services/svc.send-cart'
import { SendCartFactory } from '../../services/fac.send-cart'
import { ICartMessage } from '../../interfaces/cart-message';
import { Subscription } from 'rxjs';
import { ActiveCartService } from '@k-core/services/active-cart.service';


/**
 * @name SubmitComponent
 * @description Creates a submit partial view for the send-cart checkout, with implementation to send a cart and to close a cart
 * @author Kasper Hansen
 * @since 07-01-2019
 */
@Component({
    moduleId: module.id+ '',
    selector: 'send-cart-submit',
    templateUrl: './template/t--submit.pug',
    styleUrls: ['sty.submit.scss']
})

export class SubmitComponent implements OnInit {

    // ---- Variables ---- \\
    display: boolean
    currentEmail: string = ''
    currentB2bState: string = ''
    cart: any
    quoteIdentifier: string = 'quoteId'
    hasSession: boolean
    error: string
    
    cartErrorMessage: boolean = false
    messages: ICartMessage[]

    // Subscriptions
    private subscriptions = new Subscription()


    constructor(
        private _sendCart: SendCartService,
        private _factory: SendCartFactory
    ) {

        this.subscriptions.add(

            _sendCart.cart$.subscribe((response) => {
    
                this.cart = response
    
                if(this.display == false) {
    
                    this.getCartEmail()
                }
                
            })
        )

        this.subscriptions.add(

            _sendCart.cartMessage$.subscribe((res) => {
                this.messages = res
    
                this.checkForMessageError()
            })
        )
    }

    // ---- Lifecycle hooks ---- \\
    ngOnInit() {
        this.display = false

        this.checkForSession()
    }

    ngOnDestroy() {
        
        this.subscriptions.unsubscribe()
    }

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

    /**
     * If messages contain an error, hide the submit area
     */
    checkForMessageError() {

        for(let message of this.messages) {

            if(message.type == 'error') {
                this.cartErrorMessage = true
            }
        }
    }


    /**
     * Checks if a valid `quoteIdentifier` exists from the backend, and clears existing session if it does.
     */
    checkForSession() {

        if(this._sendCart.sessionStore('has', this.quoteIdentifier)) {

            this._factory.validateSession(this._sendCart.sessionStore('get')[this.quoteIdentifier]).then((response) => {

                if(!response) {
                    this.hasSession = false
                } else {
                    this.hasSession = true
                }
            })
        }
    }


    /**
     * Toggles display and gets current email / blanks it depending on result
     */
    changeDisplay() {
        this.display = !this.display

        if(this.display == true)
            this.currentEmail = ''
        else
            this.getCartEmail()
    }


    /**
     * Pulls the current email from the Billing Address field to display if it exists
     */
    getCartEmail() {
        if(!!this.cart.billingAddress && this.cart.billingAddress.email)
            this.currentEmail = this.cart.billingAddress.email

        if(!!this.cart.billingAddress && this.cart.billingAddress.b2bcustomer)
            this.currentB2bState = this.cart.billingAddress.b2bcustomer
    }


    /**
     * Sends the cart to the given email address, and clears the session storage
     */
    sendCart() {
        if(!!this.currentEmail) {

            this.cart.sendTo = { 'email': this.currentEmail }

            // Unset the shipping method
            if(this.cart.shipping == 'none') {
                this.cart.shipping = undefined
            }


            
            this._factory.sendCart(this.cart).then((response: any) => {

                console.log(response)

                // Handles error or non-error
                if('errorMessage' in response) {
                    console.log('has errorMessage')

                    this.error = response.errorMessage
                    
                    setTimeout(() => {
                        this.error = ''
                    }, 5000)
                } else {
                    this._sendCart.sessionStore('clear')
                }

            })
        }
    }


    /**
     * Handshakes the cart element to `_factory.saveAndClose`
     */
    saveAndClose() {
        this._factory.saveAndClose(this.cart)
    }
}
