import { AfterViewChecked, Component, ElementRef, EventEmitter, Injector, Output, ViewChild, AfterViewInit, OnInit } from '@angular/core';
import { AppConsts } from '@shared/AppConsts';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AppComponentBase } from '@shared/common/app-component-base';
import { TagTypeServiceProxy, CreateTagInput, TagServiceProxy, TagTypeListDto} from '@shared/service-proxies/service-proxies';
import { ModalDirective } from 'ngx-bootstrap';
import * as _ from 'lodash';
import { finalize } from 'rxjs/operators';
declare var $: any;

@Component({
    selector: 'createTagModal',
    templateUrl: './create-tag-modal.component.html'
})
export class CreateTagModalComponent extends AppComponentBase { 
    @ViewChild('createOrEditModal', {static: false}) modal: ModalDirective;

    @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();

    active = false;
    saving = false;
    tag: CreateTagInput = new CreateTagInput();
    tagType: TagTypeListDto = new TagTypeListDto();
    tagTypeId: any;
    tagTypeFilter: TagTypeListDto = new TagTypeListDto();
    filteredTagType: any;

    constructor(
        injector: Injector,
        private _tagTypeAppService: TagTypeServiceProxy,
        private _tagAppService: TagServiceProxy
    ) {
        super(injector);
    }

    // ngAfterViewInit(){
    //     $('#selectPreview').select2({ dropdownParent: $('#createTag')});
    // }

    show(): void {
        this.tag = new CreateTagInput();
        this.tagType = new TagTypeListDto();
        this.active = true;
        this.filterTagType();
        this.tagTypeId = null;
        this.modal.show();
    }

    onShown(): void {
        $('#selectPreview').select2({ 
            placeholder: "Select.."
        });
        // $('#selectPreview').on('change', () =>  {
        //     console.log('change');
        //     var value = $('#selectPreview').val();
        //     this.tag.tagTypeId = value;
        // });
    }

    save(): void {
        // console.log(this.tagTypeId);
        this.tag.tagTypeId =  Number((<HTMLInputElement>document.getElementById('selectPreview')).value);
        this.saving = true;
        this._tagAppService.createTag(this.tag)
            .pipe(finalize(() => { this.saving = false; }))
            .subscribe(() => {
                this.notify.info(this.l('SavedSuccessfully'));
                this.close();
                this.modalSave.emit(null);
            });
    }

    close(): void {
        this.active = false;
        this.modal.hide();
    }


    filterTagType(): void {
        this._tagTypeAppService.getTagType(
            undefined,
            undefined,
            undefined,
            undefined,
            undefined
        ).subscribe(result => {
            this.filteredTagType = result.items;
        });
      }
}
