import { Component, Injector, ViewChild, ViewEncapsulation } from '@angular/core';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { AppComponentBase } from '@shared/common/app-component-base';
import { TagServiceProxy } from '@shared/service-proxies/service-proxies';
import { LazyLoadEvent } from 'primeng/components/common/lazyloadevent';
import { Paginator } from 'primeng/components/paginator/paginator';
import { Table } from 'primeng/components/table/table';
import { CreateTagModalComponent } from './create-tag-modal.component';
import { finalize } from 'rxjs/operators';

@Component({
    templateUrl: './tag.component.html',
    encapsulation: ViewEncapsulation.None,
    animations: [appModuleAnimation()]
})
export class TagComponent extends AppComponentBase {

    @ViewChild('dataTable', {static: true}) dataTable: Table;
    @ViewChild('paginator', {static: true}) paginator: Paginator;
    @ViewChild('createTagModal', {static: false}) createTagModal: CreateTagModalComponent;

    //Filters
    filterText = '';

    
    constructor(
        injector: Injector,
        private _tagservice: TagServiceProxy
    ) {
        super(injector);
    }


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

    getTags(event?: LazyLoadEvent) {
        if (this.primengTableHelper.shouldResetPaging(event)) {
            this.paginator.changePage(0);
            return;
        }
        this.spinnerService.show();
        this._tagservice.getTag(
            undefined,
            undefined,
            this.filterText,
            this.primengTableHelper.getSorting(this.dataTable),
            this.primengTableHelper.getMaxResultCount(this.paginator, event),
            this.primengTableHelper.getSkipCount(this.paginator, event)
        )
        .pipe(finalize(() => this.spinnerService.hide() ))
        .subscribe(result => {
            this.primengTableHelper.totalRecordsCount = result.totalCount;
            this.primengTableHelper.records = result.items;
        });
    }

    createTag(): void {
        this.createTagModal.show();
    }

    reloadPage(): void {
        this.paginator.changePage(this.paginator.getPage());
    }

    deleteTag(tag): void {
        this.message.confirm(
            this.l('AreYouSure'),
            (isConfirmed) => {
                if (isConfirmed) {
                    this._tagservice.deleteTag(tag)
                        .subscribe(() => {
                            this.reloadPage();
                            this.notify.success(this.l('SuccessfullyDeleted'));
                        });
                }
            }
        );
    }

}
