import { HttpClient } from '@angular/common/http'
import { Component } from '@angular/core'
import { FormControl, FormGroup, Validators } from '@angular/forms'
import { HelperService } from '@k-core/services/svc.helper'
import { map } from 'rxjs/operators'

interface CustomDessin {
    dessinnummer: string;
    nav_type: string;
    nav_varenr: string;
    prisgruppe: string;
    tekstilhøjde: number;
    tekstilbredde: number;
}

interface Data {
    enabled: boolean;
    list: CustomDessin[];
}

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

export class CustomDessinComponent {

    isEnabled: boolean = false
    form = new FormGroup({
        dessinId: new FormControl('')
    })
    
    validatorClass: boolean = undefined
    
    customDessin: boolean = false
    comparatorArray: CustomDessin[] = []
    comparatorLength: number = 7
    totalLength: number

    constructor(
        private _http: HttpClient,
        private _helper: HelperService
    ) {}

    ngOnInit() {


        this._http.get(`${this._helper.server}/feed/get/configurator-custom-dessins?key=${this._helper.apiKey}&storeId=${this._helper.storeId}&websiteId=${this._helper.websiteId}`)
            .pipe(map((response: any) => response.data))
            .subscribe((data: Data) => {
                this.isEnabled = data.enabled
                this.comparatorArray = data.list

                this.form.controls['dessinId']

            })

        this.form.valueChanges.subscribe((values) => {

            let target = this._findComparator(values.dessinId)

            // Validator controls
            if(!!target && values.dessinId.length == target.dessinnummer.length) {
                this.validatorClass = true
            } else if(values.dessinId.length == 0) {
                this.validatorClass = undefined
            } else {
                this.validatorClass = false
            } 
        })
    }


    /**
     * Finds values that match the first 6 numbers of the input
     * 
     * @param value 
     */
    private _findComparator(value) {
        return this.comparatorArray.find((item) => item.dessinnummer.substr(0, this.comparatorLength) === value.substr(0, this.comparatorLength))
    }
}
