import { AfterViewChecked, Component, ElementRef, EventEmitter, Injector, Output, ViewChild } from '@angular/core';
import { AppConsts } from '@shared/AppConsts';
import { AppComponentBase } from '@shared/common/app-component-base';
import { TagTypeServiceProxy, UpdateTagTypeInput, TagServiceProxy, UpdateTagInput, TagListDto, TagTypeListDto} from '@shared/service-proxies/service-proxies';
import { ModalDirective } from 'ngx-bootstrap';
import * as _ from 'lodash';
import { finalize } from 'rxjs/operators';

@Component({
    selector: 'updateTagModal',
    templateUrl: './update-tag-modal.component.html'
})
export class UpdateTagModalComponent extends AppComponentBase {

    @ViewChild('createOrEditModal', {static: false}) modal: ModalDirective;

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

    active = false;
    saving = false;

    tag: TagListDto = new TagListDto();
    tagUpdate: UpdateTagInput = new UpdateTagInput();
    
    tagType: TagTypeListDto = new TagTypeListDto();
    tagTypeId: any;
    tagTypeFilter: TagTypeListDto = new TagTypeListDto();
    filteredTagType: any;

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

    show(tagRecord): void {
        this.tag = tagRecord;
        // console.log(this.orderStatusType);
        this.tagTypeId = this.tag.tagType.id;
        this.active = true;
        this.modal.show();
    }

    onShown(): void {
        $('#selectPreview').select2({ 
            placeholder: "Select.."
        });
        this.filterTagType();
    }

    save(): void {
        this.saving = true;
        this.tagUpdate.name = this.tag.name;
        
        this.tagUpdate.tagTypeId =  Number((<HTMLInputElement>document.getElementById('selectPreview')).value);
        // this.tagUpdate.tagTypeId = this.tagTypeId;
        this.tagUpdate.id = this.tag.id;
        this._tagAppService.updateTag(this.tagUpdate)
            .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;
        });
      }
}
