import { Component, OnInit, OnChanges, Input, Output, EventEmitter, ChangeDetectionStrategy, Renderer2, ElementRef, OnDestroy } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { SessionService, LAYOUT_TYPE, CustomizationService } from '@pepperi/lib';
import { GROUP_BUTTONS_VIEW_TYPE } from '@pepperi/lib/group-buttons';

@Component({
    selector: 'pepperi-internal-button',
    templateUrl: './internal-button.component.html',
    styleUrls: ['./internal-button.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush,
})
export class PepperiInternalButtonComponent implements OnInit, OnChanges, OnDestroy {
    @Input() key: string = '';
    @Input() value: string = '';
    @Input() formattedValue: string = '';
    @Input() label: string = '';
    @Input() referenceObjectInternalType: any;
    @Input() type: string = 'button'; // || 'reference' || 'listofobjects' || 'Agents' || 'ContactPersons' || 'Buyers', etc
    @Input() required: boolean = false;
    @Input() disabled: boolean = false;
    @Input() readonly: boolean = false;
    @Input() xAlignment: string = '0';
    @Input() rowSpan: number = 1;

    controlType = 'button';

    @Input() form: FormGroup = null;
    @Input() showTitle: boolean = true;
    @Input() layoutType: LAYOUT_TYPE = LAYOUT_TYPE.PepperiForm;

    @Output() elementClicked: EventEmitter<any> = new EventEmitter<any>();
    @Output() valueChanged: EventEmitter<any> = new EventEmitter<any>();

    LAYOUT_TYPE = LAYOUT_TYPE;
    GROUP_BUTTONS_VIEW_TYPE = GROUP_BUTTONS_VIEW_TYPE;

    standAlone = false;
    createNewReference: boolean = false;
    referenceButtons = [
        { Value: '', Class: '', Callback: () => this.onButtonClicked(event), Icon: null },
        { Value: '', Class: 'caution', Callback: () => this.remove(event), Icon: 'system-bin' },
    ];

    constructor(public sessionService: SessionService, private customizationService: CustomizationService, private renderer: Renderer2, public hostElement: ElementRef) { }

    ngOnInit() {
        if (this.form === null) {
            this.standAlone = true;
            this.form = this.customizationService.getDefaultFromGroup(this.key, this.value, this.required, this.readonly, this.disabled);
            this.formattedValue = this.formattedValue || this.value;
            this.renderer.addClass(this.hostElement.nativeElement, CustomizationService.STAND_ALONE_FIELD_CLASS_NAME);
        }
    }

    ngOnChanges(changes: any) {
        if (this.type === 'reference') {
            this.createNewReference = this.value.length === 0;
            this.referenceButtons[0].Value = this.formattedValue;
        }
    }

    ngOnDestroy() {
        if (this.elementClicked) {
            this.elementClicked.unsubscribe();
        }
    }

    onButtonClicked(event) {
        if (this.type === 'reference') {
            let valueArr = this.value.split('/');

            this.elementClicked.emit({
                apiName: this.key,
                eventWhich: event.which,
                value: valueArr[valueArr.length - 1], //.replace(/[^a-zA-Z0-9 ]/g, ''),
                referenceObjectInternalType: this.referenceObjectInternalType,
            });
        }
        // TODO: Uncomment - this is a feature for 16.5
        // else if (this.type === 'button' && true) { // need to check if has program to run
        //     this.elementClicked.emit({
        //         apiName: this.key,
        //         eventWhich: event.which,
        //         value: this.value // should contain the program name
        //         // value: this.value.replace(/[^a-zA-Z0-9 ]/g, ''),
        //         // referenceObjectInternalType: this.referenceObjectInternalType
        //     });
        // }
        else {
            this.elementClicked.emit({ apiName: this.key, eventWhich: event.which });
        }
    }

    hrefFunction(event) {
        if (event.which === 1 /*|| event.which === 2*/) {
            this.onButtonClicked(event);
        }
    }

    openReferenceObjectInternal(event) {
        this.elementClicked.emit({ apiName: this.key, eventWhich: event.which, value: this.value, referenceObjectInternalType: this.referenceObjectInternalType });
    }

    remove(event) {
        this.value = '';
        this.valueChanged.emit({ apiName: this.key, value: this.value });
    }
}
