/**
 * @since Thu Nov 22 2018
 * @author Charles Gouldmann - Klean
 */

// NG Imports
import { Component, OnInit, OnChanges, Inject, Input, Output, EventEmitter, PLATFORM_ID, OnDestroy, SimpleChange, SimpleChanges } from '@angular/core'

// 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'
import { HttpClient } from '@angular/common/http';
import { Observable, ReplaySubject, Subject, Subscription } from 'rxjs';
import { isPlatformBrowser } from '@angular/common'
import { LocalstorageService } from '@k-core/services/general/storage'
import { delay, map, skip, take, takeLast, takeWhile, skipWhile } from 'rxjs/operators'
import { from } from 'rxjs/observable/from'
import { of } from 'rxjs/observable/of'



@Component({
    moduleId: module.id+ '',
    selector: 'configurator-child-selector',
    templateUrl: './organisms/o--child-selector.pug',
    styleUrls: ['sty.child-selector.scss']
})

export class ChildSelectorComponent implements OnInit, OnChanges, OnDestroy {

    // ---- Variables ----
    @Input('data') data: any
    @Input('type') type_id: string
    @Input('parent') parent: string
    @Input('position') position: number
    
    @Output() onSelected = new EventEmitter<any>()

    preset: any
    timeout: any = []

    website: string = website
    mediaPath = this._helper.server + 'i/'

    // State variables
    activeChild: string = ''

    
    private subscriptions = new Subscription()

    currentlySelectedParent: string
    currentTypeSource = new Subject()
    currentType$ = this.currentTypeSource.asObservable()

    constructor(
        @Inject(PLATFORM_ID) private _platformId,
        public localStorage: LocalstorageService,
        private _preset: ConfiguratorProductLoaderService,
        private _configurator: ConfiguratorService,
        private _http: HttpClient,
        private _helper: HelperService
    ) {

        if(isPlatformBrowser(this._platformId)) {

            this.subscriptions.add(
                _preset.preset$.subscribe((response) => {
    
                    if(!!response) {
                        this.preset = response
                        this.loadPreset()
                    }
                })
            )
    
            this._preset.reExpose('type_id')
        }
    }
    
    


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

        this.data.find((child) => {
            this._configurator.addSingleValueSpecMap(child.type_id, child.name)
        })

        setTimeout(() => {
            this.currentTypeSource.next(this.parent)
        }, 100)

    }

    ngOnChanges(changes: SimpleChanges) {

        if(changes.parent) {
            this.activeChild = ''
            this.currentTypeSource.next(changes.parent.currentValue)
        }
    }

    ngOnDestroy() {

        this.localStorage.removeItem('type')
        this.subscriptions.unsubscribe()
    }
    
    // ---- Functions ---- \\
    /**
     * Find if static block exists for the type, and then return that specific static block, else return the parent block.
     * 
     * @param selection 
     */
    checkIfChildExists(selection) {
        return this._http.get(`${this._helper.server}feed/get/static${this._helper.key}&storeId=${this._helper.storeId}&websiteId=${this._helper.websiteId}&identifier=type-description_${selection}`)
            .pipe(map((response: {status: string}) => response.status === 'error' ? false : true))
    }

    /**
     * Sets value and emits it to parent
     * 
     * @param selection 
     * @param content 
     */
    setValue(selection: string, content: any[]) {
        
        this.currentTypeSource.next(selection)

        this.activeChild = selection

        this.checkIfChildExists(selection).subscribe((status) => {
            
            if(status) {
                this.currentTypeSource.next(selection)
            } else {
                this.currentTypeSource.next(this.parent) 
            }
            
            content['type_id'] = selection


            let child = this.data.filter((item) => item.type_id == selection)[0]
            
            // Set active
            if(child.visible && isPlatformBrowser(this._platformId)) {
                this.localStorage.setItem('type', this.activeChild)
            }

            this.onSelected.emit(content)
        })
    }


    /**
     * loads preset, and checks if preset does not include `_SUPER`
     * then exposes the type_id based on response received
     */
    loadPreset() {

        if(this.preset.type_id !== undefined && this.preset.type_id.indexOf('_SUPER') === -1) {
            let promise = new Promise(resolve => {

                resolve(null)
            }).then(() => {

                let element = this.data.find((curtain) => curtain.type_id === this.preset.type_id)

                this.setValue(this.preset.type_id, element.content)
            })
            .finally(() => {

                // If the type is not visible, rewrite the type
                setTimeout(() => {
                    
                    let element = this.data.find((curtain) => curtain.type_id === this.preset.type_id)

                    if(!!element && !element.visible) {
                    
                        let itemId = this.preset.type_id
                        let itemIdArray = itemId.split('_')
    
                        itemIdArray.pop()
    
                        // console.log( this.data.find((curtain) => curtain.type_id.includes(itemIdArray.join('_')) && curtain.visible) )
                        this.activeChild = this.data.find((curtain) => curtain.type_id.includes(itemIdArray.join('_')) && curtain.visible).type_id
                        this.localStorage.setItem('type', this.activeChild)
                    }
                }, 500)
            })
        }
    }
}
