/**
 * Made by mkcomponent.sh
*/

import { isPlatformBrowser } from '@angular/common'
import { Component, Input, Output, EventEmitter, Inject, PLATFORM_ID } from '@angular/core'
import { FormControl, Validators } from '@angular/forms'
import { Subscription } from 'rxjs'
import { take } from 'rxjs/operators'
import { ISubscription } from 'rxjs/Subscription'

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

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

export class MarkingComponent {

    // ---- Variables ---- \\
    @Input('position') public position: number
    @Output() private setMarking = new EventEmitter
    
    
    private preset: any
    private loadPreset: boolean = true
    private subscriptions: Subscription = new Subscription()

    public marking: FormControl = new FormControl('')

    constructor(
        @Inject(PLATFORM_ID) private _platformId,
        private _preset: ConfiguratorProductLoaderService
    ) {
        
        if(isPlatformBrowser(this._platformId)) {

            this.subscriptions.add(
                _preset.preset$.pipe(take(1)).subscribe((response) => {
                    this.preset = response
        
                    this.marking.patchValue(this.preset.marking)
                    this.loadPreset = false
                })
            )
    
            _preset.reExpose('marking')
    
            // Sanitizer regex
            const regex = /[?'^"!\(\)\{\}\\\/]/gi
    
            this.subscriptions.add(
                this.marking.valueChanges.subscribe(async (value) => {
        
                    if(regex.test(value)) {
                        await this.marking.patchValue(value.replace(regex, ''))
                    }
        
                    this.exposeMark()
                })
            )
        }
    }


    // ---- Lifecycle hooks ---- \\

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


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


    /**
     * Exposes the marking value through eventEmitter
     */
    exposeMark() {

        if(this.marking.valid && !!this.marking.value) {
            this.setMarking.emit(this.marking.value)
        }
    }
}