import { Component, OnInit } from '@angular/core';
import { ControlContainer, NgForm } from '@angular/forms';

import { BaseInputComponent } from 'first-npm-package-nicule/forms';

@Component({
    templateUrl: 'select-other-field.component.html',
    styleUrls: ['select-other-field.component.scss'],
    viewProviders: [{ provide: ControlContainer, useExisting: NgForm }]
})
export class SelectOtherFieldComponent extends BaseInputComponent implements OnInit {
    showTextField = false;
    selectValue = '';
    textFieldValue = '';

    isOtherSelected = undefined;

    ngOnInit(): void {
        this.ngModel.control.valueChanges.subscribe(data => {

            switch (this.isOtherSelected) {
                case false: {
                    this.showTextField = false;
                    break;
                }
                case true: {
                    this.showTextField = true;
                    this.textFieldValue = data;
                    break;
                }
                default: {
                    if (!data || this.options.find(item => item.value === data)) {
                        this.selectValue = data;
                        this.showTextField = false;
                    } else {
                        this.selectValue = 'other';
                        this.textFieldValue = data;
                        this.showTextField = true;
                    }
                }
            }

        });
    }

    onSelect(select): void {
        select.close();
        this.isOtherSelected = select.value === 'other';
        this.ngModel.control.setValue(!this.isOtherSelected ? select.value : '');
    }

    onKeyUp(textField): void {
        this.ngModel.control.setValue(textField._control.value);
    }

    get otherSelectOption(): string {
        return this.labelingService.label(this.field.name, this.form.name, 'otherSelectOption');
    }
}
