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 || pagination === 'infinite-scroll') { %>
import JhiDataUtils from '@/shared/data/data-utils.service';
<% } %>
import <%= entityAngularName %>Service from './<%= entityFileName %>.service';

@Component({
  mixins: [Vue2Filters.mixin]
})
export default class <%= entityAngularName %> extends <% if (fieldsContainBlob || pagination === 'infinite-scroll') { %>mixins(JhiDataUtils)<% } else { %>Vue<% } %> {
  @Inject('<%= entityInstance %>Service') private <%= entityInstance %>Service: () => <%= entityAngularName %>Service;
  <%_ if (searchEngine === 'elasticsearch') { _%>
  public currentSearch = '';
  <%_ } _%>
  private removeId: <% if (primaryKey.type === 'String'  || primaryKey.type === 'UUID') { %>string<% } else { %>number<% } %> = null;
  <%_ if (pagination !== 'no') { _%>
  public itemsPerPage = 20;
  public queryCount: number = null;
  public page = 1;
  public previousPage = 1;
  public propOrder = 'id';
  public reverse = false;
  public totalItems = 0;
  <%_ } _%>
  <%_ if (pagination === 'infinite-scroll') { _%>
  public infiniteId = +new Date();
  public links = {};
  <%_ } _%>

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

  public isFetching = false;

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

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

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

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

  public retrieveAll<%= entityAngularName %>s() :void {
    this.isFetching = true;
    <% if (pagination !== 'no') { %>
    const paginationQuery = {
      page: this.page - 1,
      size: this.itemsPerPage,
      sort: this.sort()
    };<% } %>
    <%_ if (searchEngine === 'elasticsearch') { _%>
    if (this.currentSearch) {
      this.<%= entityInstance %>Service().search(this.currentSearch<%_ if (pagination !== 'no') { _%>, paginationQuery<%_ } _%>).then(res => {
        <%_ if (pagination === 'no') { _%>
        this.<%= entityInstancePlural %> = res;
        <%_ } else if (pagination !== 'infinite-scroll') { _%>
        this.<%= entityInstancePlural %> = res.data;
        <%_ } else if (pagination === 'infinite-scroll') { _%>
        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 (pagination !== 'no') { _%>
        this.totalItems = Number(res.headers['x-total-count']);
        this.queryCount = this.totalItems;
        <%_ } _%>
        this.isFetching = false;
        <%_ if (pagination === 'infinite-scroll') { _%>
        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;
      });
      return;
    }
    <%_ } _%>
    this.<%= entityInstance %>Service().retrieve(<%_ if (pagination !== 'no') { _%>paginationQuery<%_ } _%>).then(res => {
      <%_ if (pagination !== 'infinite-scroll') { _%>
      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 (pagination !== 'no') { _%>
      this.totalItems = Number(res.headers['x-total-count']);
      this.queryCount = this.totalItems;
      <%_ } _%>
      this.isFetching = false;
      <%_ if (pagination === 'infinite-scroll') { _%>
      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;
    });
  }

  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 (pagination === 'infinite-scroll') { _%>
      this.reset();
      <%_ } else {_%>
      this.retrieveAll<%= entityAngularName %>s();
      <%_ } _%>
      this.closeDialog();
    });
  }

  <%_ } _%>
  <%_ if (pagination === 'infinite-scroll') { _%>
  public loadMore($state): void {
    if (!this.isFetching) {
      this.page++;
      this.transition();
    }
  }

  <%_ } _%>
  <%_ if (pagination !== 'no') { _%>
  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 (pagination !== 'infinite-scroll') { _%>
    this.transition();
    <%_ } else { _%>
    this.reset();
    <%_ } _%>

  }

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