import { mixins } from 'vue-class-component';

import { Component, Vue, Inject } from 'vue-property-decorator';
import Vue2Filters from 'vue2-filters';
import { I<%= entityAngularName %> } from '@/shared/model/<%= entityModelFileName %>.model';
<% if (fieldsContainBlob || paginationInfiniteScroll) { %>
import JhiDataUtils from '@/shared/data/data-utils.service';
<% } %>
import <%= entityAngularName %>Service from './<%= entityFileName %>.service';
import AlertService from '@/shared/alert/alert.service';

@Component({
  mixins: [Vue2Filters.mixin]
})
export default class <%= entityAngularName %> extends <% if (fieldsContainBlob || paginationInfiniteScroll) { %>mixins(JhiDataUtils)<% } else { %>Vue<% } %> {
  @Inject('<%= entityInstance %>Service') private <%= entityInstance %>Service: () => <%= entityAngularName %>Service;
  @Inject('alertService') private alertService: () => AlertService;

<%_ if (searchEngine) { _%>
  public currentSearch = '';
<%_ } _%>
  private removeId: <%- getTypescriptKeyType(primaryKey) %> = null;
<%_ if (!paginationNo) { _%>
  public itemsPerPage = 20;
  public queryCount: number = null;
  public page = 1;
  public previousPage = 1;
  public propOrder = 'id';
  public reverse = false;
  public totalItems = 0;
<%_ } _%>
<%_ if (paginationInfiniteScroll) { _%>
  public infiniteId = +new Date();
  public links = {};
<%_ } _%>

  public <%= entityInstancePlural %>: I<%= entityAngularName %>[] = [];

  public isFetching = false;

  public mounted(): void {
    this.retrieveAll<%= entityAngularName %>s();
  }

<%_ if (searchEngine) { _%>
  public search(query) : void {
    if (!query) {
      return this.clear();
    }
    this.currentSearch = query;
    this.retrieveAll<%= entityAngularName %>s();
  }

<%_ } _%>
  public clear() : void {
<%_ if (searchEngine) { _%>
    this.currentSearch = '';
<%_ } _%>
<%_ if (!paginationNo) { _%>
    this.page = 1;
<%_ } _%>
<%_ if (paginationInfiniteScroll) { _%>
    this.links = {};
    this.infiniteId += 1;
    this.<%= entityInstancePlural %> = [];
<%_ } _%>
    this.retrieveAll<%= entityAngularName %>s();
  }

<%_ if (paginationInfiniteScroll) { _%>
  public reset(): void {
    this.page = 1;
    this.infiniteId += 1;
    this.<%= entityInstancePlural %> = [];
    this.retrieveAll<%= entityAngularName %>s();
  }
<%_ } _%>

  public retrieveAll<%= entityAngularName %>s() :void {
    this.isFetching = true;
<%_ if (!paginationNo) { _%>
    const paginationQuery = {
      page: this.page - 1,
      size: this.itemsPerPage,
      sort: this.sort()
    };
<%_ } _%>
<%_ if (searchEngine) { _%>
    if (this.currentSearch) {
      this.<%= entityInstance %>Service().search(this.currentSearch<%_ if (!paginationNo) { _%>, paginationQuery<%_ } _%>).then(res => {
  <%_ if (paginationNo) { _%>
        this.<%= entityInstancePlural %> = res;
  <%_ } else if (!paginationInfiniteScroll) { _%>
        this.<%= entityInstancePlural %> = res.data;
  <%_ } else if (paginationInfiniteScroll) { _%>
        if (res.data && res.data.length > 0) {
          for (let i = 0; i < res.data.length; i++) {
            this.<%= entityInstancePlural %>.push(res.data[i]);
          }
          if (res.headers && res.headers['link']) {
            this.links = this.parseLinks(res.headers['link']);
          }
        }
  <%_ } _%>
  <%_ if (!paginationNo) { _%>
        this.totalItems = Number(res.headers['x-total-count']);
        this.queryCount = this.totalItems;
  <%_ } _%>
        this.isFetching = false;
  <%_ if (paginationInfiniteScroll) { _%>
        if ((<any>this.$refs.infiniteLoading)) {
          (<any>this.$refs.infiniteLoading).stateChanger.loaded();
          if (this.links !== {} && this.page > this.links['last']) {
            (<any>this.$refs.infiniteLoading).stateChanger.complete();
          }
        }
  <%_ } _%>
      }, err => {
        this.isFetching = false;
        this.alertService().showHttpError(this,err.response);
      });
      return;
    }
<%_ } _%>
    this.<%= entityInstance %>Service().retrieve(<%_ if (!paginationNo) { _%>paginationQuery<%_ } _%>).then(res => {
<%_ if (!paginationInfiniteScroll) { _%>
      this.<%= entityInstancePlural %> = res.data;
<%_ } else { _%>
      if (res.data && res.data.length > 0) {
        for (let i = 0; i < res.data.length; i++) {
          this.<%= entityInstancePlural %>.push(res.data[i]);
        }
        if (res.headers && res.headers['link']) {
          this.links = this.parseLinks(res.headers['link']);
        }
      }
<%_ } _%>
<%_ if (!paginationNo) { _%>
      this.totalItems = Number(res.headers['x-total-count']);
      this.queryCount = this.totalItems;
<%_ } _%>
      this.isFetching = false;
<%_ if (paginationInfiniteScroll) { _%>
      if ((<any>this.$refs.infiniteLoading)) {
        (<any>this.$refs.infiniteLoading).stateChanger.loaded();
        if (this.links !== {} && this.page > this.links['last']) {
          (<any>this.$refs.infiniteLoading).stateChanger.complete();
        }
      }
<%_ } _%>
    }, err => {
      this.isFetching = false;
      this.alertService().showHttpError(this,err.response);
    });
  }

  public handleSyncList(): void {
    this.clear();
  }

<%_ if (!readOnly) { _%>
  public prepareRemove(instance: I<%= entityAngularName %>) : void {
    this.removeId = instance.id;
    if (<any>this.$refs.removeEntity) {
      (<any>this.$refs.removeEntity).show();
    }
  }

  public remove<%= entityAngularName %>() : void {
    this.<%= entityInstance %>Service().delete(this.removeId).then(() => {
  <%_ if (enableTranslation) { _%>
      const message = this.$t('<%= i18nAlertHeaderPrefix %>.deleted', { 'param' : this.removeId });
  <%_ } else {_%>
      const message = 'A <%= entityAngularName %> is deleted with identifier ' + this.removeId;
  <%_ } _%>
      this.$bvToast.toast(message.toString(), {
        toaster: 'b-toaster-top-center',
        title: 'Info',
        variant: 'danger',
        solid: true,
        autoHideDelay: 5000,
      });
      this.removeId = null;
  <%_ if (paginationInfiniteScroll) { _%>
      this.reset();
  <%_ } else {_%>
      this.retrieveAll<%= entityAngularName %>s();
  <%_ } _%>
      this.closeDialog();
    }).catch(error => {
      this.alertService().showHttpError(this,error.response);
    });
  }

<%_ } _%>
<%_ if (paginationInfiniteScroll) { _%>
  public loadMore($state): void {
    if (!this.isFetching) {
      this.page++;
      this.transition();
    }
  }

<%_ } _%>
<%_ if (!paginationNo) { _%>
  public sort() : Array<any> {
    const result = [this.propOrder + ',' + (this.reverse ? 'desc' : 'asc')];
    if (this.propOrder !== 'id') {
      result.push('id');
    }
    return result;
  }

  public loadPage(page: number) : void {
    if (page !== this.previousPage) {
      this.previousPage = page;
      this.transition();
    }
  }

  public transition() : void {
    this.retrieveAll<%= entityAngularName %>s();
  }

  public changeOrder(propOrder) : void {
    this.propOrder = propOrder;
    this.reverse = !this.reverse;
  <%_ if (!paginationInfiniteScroll) { _%>
    this.transition();
  <%_ } else { _%>
    this.reset();
  <%_ } _%>

  }

<%_ } _%>
  public closeDialog() : void {
    (<any>this.$refs.removeEntity).hide();
  }
}
