import { Component,<% if (!fieldsContainBlob) { %> Vue,<% } %> Inject } from 'vue-property-decorator';
<% if (fieldsContainBlob) { %>
  import { mixins } from 'vue-class-component';
  import JhiDataUtils from '@/shared/data/data-utils.service';
<% } %>
import { numeric, required, minLength, maxLength, minValue, maxValue } from 'vuelidate/lib/validators';
<%_
    let dateFnsIncluded = false;
    for (idx in fields) {
        const fieldName = fields[ idx ].fieldName;
        const fieldType = fields[idx].fieldType;
        if ([ 'Instant', 'ZonedDateTime' ].includes(fieldType) && !dateFnsIncluded) {
            dateFnsIncluded = true;
_%>
import format from 'date-fns/format';
import parse from 'date-fns/parse';
import parseISO from 'date-fns/parseISO';
import { DATE_TIME_LONG_FORMAT } from '@/shared/date/filters';
    <%_ } } _%>

<%_
    const importEntitiesSeen = [entityAngularName];
    let hasManyToMany = false;
    for (idx in relationships) {
      if (!relationships[idx].otherEntityIsEmbedded) {
        const otherEntityAngularName = relationships[idx].otherEntityAngularName;
        const otherEntityFileName = relationships[idx].otherEntityFileName;
        const otherEntityFolderName = relationships[idx].otherEntityFileName;
        const otherEntityModelName = relationships[idx].otherEntityModelName;
        if (relationships[idx].relationshipType === 'many-to-many' && relationships[idx].ownerSide === true) {
          hasManyToMany = true;
        }
_%>
  <% if (otherEntityAngularName === 'User' && authenticationType !== 'oauth2') { %>
import UserService from '@/admin/user-management/user-management.service';
  <% } else if (otherEntityAngularName !== 'User' && !importEntitiesSeen.includes(otherEntityAngularName)) { %>
import <%= otherEntityAngularName %>Service from '../<%= otherEntityFolderName %>/<%= otherEntityFileName %>.service';
import { I<%= otherEntityAngularName %> } from '@/shared/model/<%= otherEntityModelName %>.model';
  <% } %>
<%_ importEntitiesSeen.push(otherEntityAngularName); } } _%>
import AlertService from '@/shared/alert/alert.service';
import { I<%= entityAngularName %>, <%= entityAngularName %> } from '@/shared/model/<%= entityModelFileName %>.model';
import <%= entityAngularName %>Service from './<%= entityFileName %>.service';

const validations: any = {
  <%= entityInstance %>: {
    <%_ for (idx in fields) {
      const fieldName = fields[idx].fieldName;
      const fieldType = fields[idx].fieldType;
    _%>
    <%= fieldName %>:  {
    <%_ if (fields[idx].fieldValidate === true) { _%>
    <%_ if (fields[idx].fieldValidateRules.includes('required')) { _%>
    required,
    <%_ } _%>
    <%_ if (fields[idx].fieldValidateRules.includes('minlength')) { _%>
      minLength: minLength(<%= fields[idx].fieldValidateRulesMinlength %>),
    <%_ } _%>
    <%_ if (fields[idx].fieldValidateRules.includes('maxlength')) { _%>
      maxLength: maxLength(<%= fields[idx].fieldValidateRulesMaxlength %>),
    <%_ } _%>
    <%_ if (['Integer', 'Long', 'Float', 'Double', 'BigDecimal', 'Duration'].includes(fieldType)) { _%>
    numeric,
    <%_ if (fields[idx].fieldValidateRules.includes('min')) { _%>
      min: minValue(<%= fields[idx].fieldValidateRulesMin %>),
    <%_ } _%>
    <%_ if (fields[idx].fieldValidateRules.includes('max')) { _%>
      max: maxValue(<%= fields[idx].fieldValidateRulesMax %>),
    <%_ } _%>
    <%_ } _%>

    <%_ } _%>
    },
    <%_ } _%>
    <%_
    for (idx in relationships) {
      if (relationships[idx].relationshipValidate === true) { _%>
    <%= relationships[idx].relationshipFieldName %><%_ if (dto !== 'no') { _%>Id<%_ } _%>: {
      required
    },
    <%_ } _%>
  <%_ } _%>
  }
};

@Component({
  validations
})
export default class <%= entityAngularName %>Update extends <% if (fieldsContainBlob) { %>mixins(JhiDataUtils)<% } else { %>Vue<% } %> {
  @Inject('alertService') private alertService: () => AlertService;
  @Inject('<%= entityInstance %>Service') private <%= entityInstance %>Service: () => <%= entityAngularName %>Service;
  public <%= entityInstance %>: I<%= entityAngularName %> = new <%= entityAngularName %>();
  <%_
    const entitiesSeen = [entityAngularName];
    for (idx in relationships) {
      if (!relationships[idx].otherEntityIsEmbedded) {
        const otherEntityName = relationships[idx].otherEntityName;
        const otherEntityNamePlural = relationships[idx].otherEntityNamePlural;
        const otherEntityAngularName = relationships[idx].otherEntityAngularName;
        if (!(otherEntityAngularName === 'User' && authenticationType === "oauth2")) {
  _%>
  <%_ if (!entitiesSeen.includes(otherEntityAngularName)) { %>
  @Inject('<%= otherEntityName %>Service') private <%= otherEntityName %>Service: () => <%= otherEntityAngularName %>Service;
  <%_ } _%>
  <%_ if (!entitiesSeen.includes(otherEntityNamePlural)) { %>
  public <%= otherEntityNamePlural %> : <% if (otherEntityAngularName === 'User') { %>Array<any><%_ } else { _%>I<%= otherEntityAngularName %>[]<%_ } _%> = [];
  <%_ } _%>
  <%_ entitiesSeen.push(otherEntityAngularName);entitiesSeen.push(otherEntityNamePlural); } } } _%>
  public isSaving = false;
  public currentLanguage = '';

  beforeRouteEnter(to, from, next) {
    next(vm => {
      if (to.params.<%= entityInstance %>Id) {
        vm.retrieve<%= entityAngularName %>(to.params.<%= entityInstance %>Id);
      }
      <%_ if (relationships.length > 0) { _%>
      vm.initRelationships();
      <%_ } _%>
    });
  }

  created(): void {
    this.currentLanguage = this.$store.getters.currentLanguage;
    this.$store.watch(
      () => this.$store.getters.currentLanguage,
      () => {
        this.currentLanguage = this.$store.getters.currentLanguage;
      }
    );
    <%_ if (hasManyToMany) { _%>
    <%_
      for (idx in relationships) {
      const otherEntityNamePlural = relationships[idx].otherEntityNamePlural;
      if (relationships[idx].relationshipType === 'many-to-many' && relationships[idx].ownerSide === true) {
      const relationshipFieldNamePlural = relationships[idx].relationshipFieldNamePlural;
    _%>
    this.<%= entityInstance %>.<%= relationshipFieldNamePlural %> = [];
    <%_ } } _%>
    <%_ } _%>
  }

  public save() : void {
    this.isSaving = true;
    <%_ for (idx in fields) {
        const fieldName = fields[ idx ].fieldName;
        const fieldType = fields[idx].fieldType;
    } _%>
    if (this.<%= entityInstance %>.id) {
      this.<%= entityInstance %>Service().update(this.<%= entityInstance %>).then((param) => {
        this.isSaving = false;
        this.$router.go(-1);
        <%_ if (enableTranslation) { _%>
        const message = this.$t('<%= i18nKeyPrefix %>.updated', { 'param' : param.id });
        <%_ } else {_%>
        const message = 'A <%= entityAngularName %> is updated with identifier ' + param.id;
        <%_ } _%>
        this.alertService().showAlert(message, 'info');
      });
    } else {
      this.<%= entityInstance %>Service().create(this.<%= entityInstance %>).then((param) => {
        this.isSaving = false;
        this.$router.go(-1);
        <%_ if (enableTranslation) { _%>
        const message = this.$t('<%= i18nKeyPrefix %>.created', { 'param' : param.id });
        <%_ } else {_%>
        const message = 'A <%= entityAngularName %> is created with identifier ' + param.id;
        <%_ } _%>
        this.alertService().showAlert(message, 'success');
      });
    }
  }

  <%_
    let dateFunctionIncluded = false;
    for (idx in fields) {
        const fieldName = fields[ idx ].fieldName;
        const fieldType = fields[idx].fieldType;
        if ([ 'Instant', 'ZonedDateTime' ].includes(fieldType) && !dateFunctionIncluded) {
            dateFunctionIncluded = true;
  _%>
    public convertDateTimeFromServer(date: Date): string {
      if (date) {
        return format(date, DATE_TIME_LONG_FORMAT);
      }
      return null;
    }

    public updateInstantField(field, event) {
      if (event.target.value) {
        this.<%= entityInstance %>[field] = parse(event.target.value, DATE_TIME_LONG_FORMAT, new Date());
      } else {
        this.<%= entityInstance %>[field] = null;
      }
    }

    public updateZonedDateTimeField(field, event) {
      if (event.target.value) {
        this.<%= entityInstance %>[field] = parse(event.target.value, DATE_TIME_LONG_FORMAT, new Date())
      } else {
        this.<%= entityInstance %>[field] = null;
      }
    }
    <%_ } } _%>

  public retrieve<%= entityAngularName %>(<%= entityInstance %>Id) : void {
    this.<%= entityInstance %>Service().find(<%= entityInstance %>Id).then((res) => {
<%_
        for (idx in fields) {
            const fieldName = fields[idx].fieldName;
            const fieldType = fields[idx].fieldType;
            if ([ 'Instant', 'ZonedDateTime' ].includes(fieldType)) {
_%>
      res.<%= fieldName %> = new Date(res.<%= fieldName %>);
<%_ } } _%>
      this.<%= entityInstance %> = res;
    });
  }

  public previousState() : void {
    this.$router.go(-1);
  }

  <%_ if (fieldsContainBlob && fieldsContainImageBlob) { _%>
  public clearInputImage(field, fieldContentType, idInput) : void {
    if (this.<%= entityInstance %> && field && fieldContentType) {
      if (this.<%= entityInstance %>.hasOwnProperty(field)) {
        this.<%= entityInstance %>[field] = null;
      }
      if (this.<%= entityInstance %>.hasOwnProperty(fieldContentType)) {
        this.<%= entityInstance %>[fieldContentType] = null;
      }
      if (idInput) {
        (<any>this).$refs[idInput] = null;
      }
    }
  }

  <%_ } _%>
  public initRelationships() : void {
    <%_
        for (idx in relationships) {
          if (!relationships[idx].otherEntityIsEmbedded) {
          const otherEntityName = relationships[idx].otherEntityName;
          const otherEntityNamePlural = relationships[idx].otherEntityNamePlural;
          const otherEntityAngularName = relationships[idx].otherEntityAngularName;
          if (!(otherEntityAngularName === 'User' && authenticationType === "oauth2")) {
    _%>
    this.<%= otherEntityName %>Service().retrieve().then((res) => {
      this.<%= otherEntityNamePlural %> = res.data;
    });
    <%_ } } } _%>
  }

  <%_ if (hasManyToMany) { _%>
  public getSelected(selectedVals, option) : any {
    if (selectedVals) {
      for (let i = 0; i < selectedVals.length; i++) {
        if (option.id === selectedVals[i].id) {
          return selectedVals[i];
        }
      }
    }
    return option;
  }
  <%_ } _%>
}
