import { Component, OnInit, OnDestroy, Input } from '@angular/core';
import { HttpErrorResponse,  HttpHeaders, HttpResponse } from '@angular/common/http';
import { Subscription } from 'rxjs/Subscription';
import { JhiEventManager, JhiParseLinks, JhiAlertService, JhiDataUtils } from 'ng-jhipster';

import { I<%= entityAngularName %> } from 'app/shared/model/<%= entityModelFileName %>.model';
import { Principal } from 'app/core';

import { ITEMS_PER_PAGE } from 'app/shared';
import { Subject } from 'rxjs/Subject';
import { ClrDatagridSortOrder, ClrDatagridStateInterface } from '@clr/angular';
import { SEARCH_DEBOUNCE_TIME } from 'app/shared/constants/load.constants';
import { <%= entityAngularName %>Service } from './<%= entityFileName %>.service';

import { resolveFilter } from 'app/shared/util/filter-util';
import { Router } from '@angular/router';

@Component({
    selector: '<%= jhiPrefixDashed %>-<%= entityFileName %>-select-dialog',
    templateUrl: './<%= entityFileName %>-select-dialog.component.html',
    styleUrls: [
        './<%= entityFileName %>-select-dialog.component.scss'
    ]
})
export class <%= entityAngularName %>SelectDialogComponent implements OnInit, OnDestroy {
    <%_ if (pagination === 'pagination' || pagination === 'pager') { _%>
<%- include('select-dialog-pagination-template', {toArrayString: toArrayString}); -%>
    <%_ } else if (pagination === 'no') { _%>
<%- include('select-dialog-no-pagination-template', {toArrayString: toArrayString}); -%>
    <%_ } _%>

    get opened() {
        return this._opened;
    }

    set opened(value) {
        this._opened = value;
        if (!value) {
            this.close();
        }
    }

    ngOnInit() {
        // modify for Clarity
        <%_ if (pagination === 'no') { _%>
        this.loadAll();
        <%_ } _%>
        this.registerChangeIn<%= entityClassPlural %>();
        this.opened = true;
    }

    ngOnDestroy() {
        // fixed router into error
        if (this.eventSubscriber) {
            this.eventManager.destroy(this.eventSubscriber);
        }
        // this.eventManager.destroy(this.eventSubscriber);
    }

    trackId(index: number, item: I<%= entityAngularName %>) {
        return item.id;
    }
    <%_ if (fieldsContainBlob) { _%>
    byteSize(field) {
        return this.dataUtils.byteSize(field);
    }
    openFile(contentType, field) {
        return this.dataUtils.openFile(contentType, field);
    }
    <%_ } _%>
    <%_
    let eventCallBack = 'this.loadAll()';
    if (pagination === 'infinite-scroll') {
        eventCallBack = 'this.reset()';
    } _%>

    registerChangeIn<%= entityClassPlural %>() {
        this.eventSubscriber = this.eventManager.subscribe('<%= entityInstance %>ListModification', response => <%= eventCallBack %>);
    }

    remove(item:  I<%= entityAngularName %>) {
        for (let i = 0; i < this.selected.length; i++) {
            if (item.id === this.selected[i].id) {
                this.selected.splice(i, 1);
                return;
            }
        }
    }

    <%_ if (databaseType !== 'cassandra' && pagination !== 'no') { _%>
    sort() {
        const result = [this.predicate + ',' + (this.reverse ? 'asc' : 'desc')];
        if (this.predicate !== 'id') {
            result.push('id');
        }
        return result;
    }

    <%_ } _%>
    confirm() {
        this.callback(this.multiSelect ? [...this.selected] : [this.selected]);
        this.opened = false;
    }

    <%_ if (pagination !== 'no') { _%>
        <%_ if (pagination === 'pagination' || pagination === 'pager') { _%>
    private paginate<%= entityClassPlural %>(data: I<%= entityAngularName %>[], headers: HttpHeaders) {
        <%_ if (databaseType !== 'cassandra') { _%>
        this.totalItems = parseInt(headers.get('X-Total-Count'), 10);
        this.queryCount = this.totalItems;
        <%_ } _%>
        this.<%= entityInstancePlural %> = data;
        // added for Clarity
        this.loading = false;
        <%_ } else if (pagination === 'infinite-scroll') { _%>
        this.links = this.parseLinks.parse(headers.get('link'));
        this.totalItems = parseInt(headers.get('X-Total-Count'), 10);
        for (let i = 0; i < data.length; i++) {
            this.<%= entityInstancePlural %>.push(data[i]);
        }
        <%_ } _%>
        if (this.multiSelect) {
            data.forEach(item => {
                for (let i = 0; i < this.selected.length; i++) {
                    if (item.id === this.selected[i].id) {
                        this.selected[i] = item;
                        break;
                    }
                }
            });
        } else if (this.selected) {
            data.forEach(item => {
                if (this.selected.id === item.id) {
                    this.selected = item;
                    return false;
                }
            });
        }
    }

    <%_ } _%>
    private onError(errorMessage: string) {
        this.jhiAlertService.error(errorMessage, null, null);
    }

}
