import { Component, ElementRef, Renderer2, ViewChild, ViewChildren } from '@angular/core';

import { ControlValueAccessor, FormControl, NG_VALIDATORS, NG_VALUE_ACCESSOR, ValidationErrors } from '@angular/forms';

abstract class Evt extends EventTarget {
    abstract get value(): string;
}

@Component({
    selector: 'knk-link-to-ref-page',
    templateUrl: './linktorefpage.component.html',
    styleUrls: ['./linktorefpage.component.scss'],
    providers: [
        {
          provide: NG_VALUE_ACCESSOR,
          useExisting: LinkToRefPageComponent, // forwardRef(() => PriceComponent),
          multi: true
        }
        // {
        //   provide: NG_VALIDATORS,
        //   useExisting: UploadGraphComponent, // forwardRef(() => PriceComponent),
        //   multi: true
        // }
      ]
})
export class LinkToRefPageComponent implements ControlValueAccessor {
    items: Array<{reference: string}>;
    onChange: (param: Array<{reference: string}>) => void;

    @ViewChildren('link') linkCtrls: ElementRef[];
    @ViewChildren('comment') commentCtrls: ElementRef[];

    constructor(private renderer: Renderer2) {
    }

    writeValue(value: Array<{reference: string, comment: string}>): void {
        if (value) {
            this.items = value;
        } else {
            this.items = [{reference: ''}];
        }
        // if (this.items) {
        //     this.renderer.setProperty(this.link.nativeElement, 'value', this.imgGraph);
        //     this.renderer.setProperty(this.comment.nativeElement, 'value', this.imgGraph);
        // }
    }

    registerOnChange( fn: () => void ): void {
        this.onChange = fn;
    }

    registerOnTouched( fn: () => void ): void {
        console.log('registerOnTouched');
    }

    addRef(): void {
        this.items.push({reference: ''});
        if (this.onChange) {
            this.onChange(this.items);
        }
    }

    removeRef(index: number): void {
        this.items.splice(index, 1);
        if (this.onChange) {
            this.onChange(this.items);
        }
    }

    changeLink( $event: Event, index: number): void {
        let te: Evt = $event.target as Evt;
        this.items[index].reference = te.value;
        if (this.onChange) {
            this.onChange(this.items);
        }
        $event.stopPropagation();
    }
}
