// NG Imports
import { Component, OnInit, OnChanges, OnDestroy, Inject, Input, EventEmitter, Output } from '@angular/core'
import { Router, NavigationEnd } from '@angular/router'
import { isPlatformBrowser } from '@angular/common'

import { CookieService } from 'ng2-cookies'

// Interfaces
import { ISubscription } from 'rxjs/Subscription'

// Settings
import { website } from '@k-settings/app-setup'

// Core Services
import { HelperService } from '@k-services/svc.helper'

// Module Services
import { ConfiguratorProductLoaderService } from '../../services/svc.configurator-product-reloader'
import { ConfiguratorService }  from '../../services/svc.configurator'




/**
 * @since >Tue Sep 17 2018
 * @author Kasper Hansen - Klean
 * 
 * MODIFIED
 * @since Tue Sep 18 2018
 * @author Charles Gouldmann - Klean
 */
@Component({
    moduleId: module.id+ '',
    selector: 'configurator-parent-selector',
    templateUrl: './organisms/o--parent-selector.pug',
    styleUrls: ['sty.parent-selector.scss']
})

export class ParentSelectorComponent implements OnChanges {

    // ---- Variables ---- \\
    @Input('data') data: any
    @Output() onSelected = new EventEmitter<string>()
    preset: any
    loadPreset = true
    cookie_name: string = 'viHuskerDinKonfiguration'
    
    mediaPath = this._helper.server + 'i/'
    website: string = website

    // State variables
    activeParent: string = ''
    waitForPreset: boolean = true


    // Observable subscriptions
    private presetSubscription: ISubscription




    
    constructor(
        private _preset: ConfiguratorProductLoaderService,
        private _configurator: ConfiguratorService,
        private _helper: HelperService,
        private _router: Router,
        private _cookie: CookieService
    ) {

        // Subscribe to preset
        this.preset = _preset.GETPreset()
        this.presetSubscription =  _preset.preset$.subscribe(response => {
            this.preset = response
        })

        // Subscribe to route changes
        _router.events.subscribe((ev) => {
            if(ev instanceof NavigationEnd) {
                this.checkForRouteAndCookie()
            }
        })
    }

    


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

        new Promise((resolve) => {

            let interval = setInterval(() => {
                if(!!this.data) {

                    resolve(this.data)
                    clearInterval(interval)
                }
            }, 100)

        }).then((resp: any) => {

            resp.find((parent) => {
                this._configurator.addSingleValueSpecMap(parent.type_id, parent.name)
            })
        })
    }


    ngOnChanges() {
        if(this.data)
            this.determineDefaultOrPreset()
    }


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






    // ---- Functions ---- \\
    
    /**
     * Will set the global variable `waitForPreset` to true/false
     * depending on whether or nor type_id is found in url or cookie is set.
     * 
     * This should make `determineDefaultOrPreset()` wait a bit before continueing
     */
    checkForRouteAndCookie() {
        let wait = false

        if(isPlatformBrowser) {
            // Check if type_id exists in route
            


            if(this._router.url.includes('type_id') && this.preset !== undefined) {
                if(!!!this.preset.type_id) {
                    wait = true
                }
            }
            // If not in route, then check for it in cookie
            else if(this._cookie.get(this.cookie_name) && this.preset !== undefined) {
                if(!!!this.preset.type_id) {
                    wait = true
                }
            }
        }
        

            
        // Dont wait
        if(!wait) {
            this.waitForPreset = false
        }

    }



    
    /**
     * Emits the chosen value and sets active parent
     * 
     * TODO: stopPreset is never reset
     * 
     * @param selection 
     */
    setValue(selection: string, userInput = false) {

        // Detect if change is coming by user input or not
        if(!!userInput) {
            this._preset.stopPreset = true
        }
        else {
            this._preset.stopPreset = false
        }
        
        this.onSelected.emit(selection)

        // Set active
        this.activeParent = selection
    }



    /**
     * Will wait for preset as long as `waitForPreset` is `true` or `maxTries` has not been reached.
     * When max is reached or `waitForPreset` is set to false we assume that the data should be available
     * and check if there is any preset data. 
     * If no preset is found a default type is set, else the parent for the current preset is set.
     * 
     * TODO: Change switchcase with hardcoded values with a check for `value` in each parent
     * 
     * @param maxTries - Default is 30 == 3000 milliseconds
     * 
     * @requires waitForPreset
     * @requires setValue() - set the type
     * @requires checkForRouteAndCookie() - Check for preset in cookie or route
     */
    determineDefaultOrPreset(maxTries: number = 30) {
        let count       = 0
        

        let interval = setInterval(() => {

            if(!this.waitForPreset || count > maxTries) {

                // If preset doesnt exist, or type is not set, or type is set to _SUPER, set it to the first category
                if(!this.preset || this.preset.type_id === undefined || this.preset.type_id === '_SUPER' || !this.preset.type_id) {
                    this.setValue(this.data[0].type_id)      
                }
                else {

                    let value = this.preset.type_id.split('_')[0]

                    switch(value) {
                        case 'VELUX':
                            this.setValue(`${this.preset.type_id.split('_')[1]}_SUPER`)
                            break
                        case 'ROD':
                            this.setValue('CURT_SUPER')
                            break
                        case 'KUPON':
                            this.setValue('CURT_SUPER')
                            break
            
                        default:
                            this.setValue(value + '_SUPER')
                            break
                    }
                }

                clearInterval(interval)
            }

            this._preset.readQuery()
            this.preset = this._preset.GETPreset()
            this.checkForRouteAndCookie()

            count++
        }, 100)
    }




    /**
     * Set Type (Type, Mål, color, Detailer)
    */
    setSelector(selector_id) {
        this._configurator.setSpecSelector(selector_id)
    }

}