import { Component, ViewChild, Injector, Output, EventEmitter} from '@angular/core';
import { ModalDirective } from 'ngx-bootstrap';
import { finalize } from 'rxjs/operators';
import { TagsServiceProxy, CreateOrEditTagDto, TagTypeServiceProxy } from '@shared/service-proxies/service-proxies';
import { AppComponentBase } from '@shared/common/app-component-base';
import * as moment from 'moment';


@Component({
    selector: 'createOrEditTagModal',
    templateUrl: './create-or-edit-tag-modal.component.html'
})
export class CreateOrEditTagModalComponent extends AppComponentBase {

    @ViewChild('createOrEditModal', { static: true }) modal: ModalDirective;
    @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();

    active = false;
    saving = false;
    filteredTagType: any;

    tag: CreateOrEditTagDto = new CreateOrEditTagDto();

    constructor(
        injector: Injector,
        private _tagsServiceProxy: TagsServiceProxy,
        private _tagTypeAppService: TagTypeServiceProxy
    ) {
        super(injector);
    }

    ngOnInit(){
        this.filterTagType();
        // $('#selectTagType').select2({ 
        //     placeholder: "Select.."
        // });
        
    }

    show(tagId?: number): void {
        // $('#selectTagType').select2({ 
        //     placeholder: "Select.."
        // });
        if (!tagId) {
            this.tag = new CreateOrEditTagDto();
            this.tag.id = tagId;

            this.active = true;
            this.modal.show();
        } else {
            this._tagsServiceProxy.getTagForEdit(tagId).subscribe(result => {
                this.tag = result.tag;
                console.log(this.tag);
                this.active = true;
                this.modal.show();
            });
        }
    }

    save(): void {
            this.saving = true;
            this.tag.tagTypeId = Number((<HTMLInputElement>document.getElementById('selectTagType')).value);
            this._tagsServiceProxy.createOrEdit(this.tag)
             .pipe(finalize(() => { this.saving = false;}))
             .subscribe(() => {
                this.notify.info(this.l('SavedSuccessfully'));
                this.close();
                this.modalSave.emit(null);
             });
    }

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







    close(): void {

        this.active = false;
        this.modal.hide();
    }
}
