<%#
 Copyright 2013-2025 the original author or authors from the JHipster project.

 This file is part of the JHipster project, see https://www.jhipster.tech/
 for more information.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      https://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-%>
import React, { useState, useEffect } from 'react';
import { Link, useNavigate, useParams } from 'react-router-dom';
import {
  Button,
  Row,
  Col,
  FormText,
  <% if (anyFieldHasDocumentation) { %>UncontrolledTooltip,<% } %>
} from 'reactstrap';
import {
  isNumber,
  Translate,
  translate,
  ValidatedField,
  ValidatedForm,
  <% if (anyFieldHasFileBasedContentType) { %> ValidatedBlobField,<% } %>
} from 'react-jhipster';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';

import { convertDateTimeFromServer, convertDateTimeToServer, displayDefaultDateTime } from 'app/shared/util/date-utils';
<%_ if (relationships.filter(e => e.relationshipManyToMany) !== undefined) { _%>
import { mapIdList } from 'app/shared/util/entity-utils';
<%_ } _%>
import { useAppDispatch, useAppSelector } from 'app/config/store';

<%_
let otherEntityActions = new Set();

for (const otherEntity of otherEntitiesWithPersistableRelationship) {
    otherEntityActions.add({
      action: `get${otherEntity.entityNamePlural}`,
      instance: otherEntity.entityInstancePlural,
      entity: otherEntity.entityAngularName,
      reducer: otherEntity.builtInUser ? `userManagement.${otherEntity.entityInstancePlural}` : `${otherEntity.entityReactState}.entities`
    });
  if (otherEntity.builtInUser) {
_%>
import { I<%= otherEntity.entityAngularName %> } from 'app/shared/model/user.model';
    <%_ if (authenticationTypeOauth2) { _%>
import { getUsers } from 'app/shared/reducers/user-management';
    <%_ } else { _%>
import { getUsers } from 'app/modules/administration/user-management/user-management.reducer';
    <%_ } _%>
  <%_ } else { _%>
    <%_ if (otherEntity.entityAngularName !== entityReactName) { _%>
import { I<%= otherEntity.entityAngularName %> } from 'app/shared/model/<%= otherEntity.entityModelFileName %>.model';
    <%_ } _%>
import { getEntities as get<%= otherEntity.entityNamePlural %> } from 'app/entities/<%= otherEntity.entityFolderName %>/<%= otherEntity.entityFileName %>.reducer';
  <%_ } _%>
<%_ } _%>
import { I<%= entityReactName %> } from 'app/shared/model/<%= entityModelFileName %>.model';
<%_ const enumImports = this.generateEntityClientEnumImports(fields); _%>
<%_ enumImports.forEach( (importedPath, importedType) => { _%>
import { <%- importedType %> } from '<%- importedPath %>';
<%_ }); _%>
import {
  getEntity,
  updateEntity,
  createEntity,
  reset
} from './<%= entityFileName %>.reducer';

export const <%= entityReactName %>Update = () => {
  const dispatch = useAppDispatch();

  const navigate = useNavigate();

  const { id } = useParams<'id'>();
  const isNew = id === undefined;


  <%_ otherEntityActions.forEach(val => { _%>
  const <%= val.instance %> = useAppSelector(state => state.<%= val.reducer %>);
  <%_ }) _%>
  const <%= entityInstance %>Entity = useAppSelector(state => state.<%= entityReactState %>.entity);
  const loading = useAppSelector(state => state.<%= entityReactState %>.loading);
  const updating = useAppSelector(state => state.<%= entityReactState %>.updating);
  const updateSuccess = useAppSelector(state => state.<%= entityReactState %>.updateSuccess);
  <%_ enumImports.forEach( (importedPath, importedType) => { _%>
  const <%- this._.lowerFirst(importedType) %>Values = Object.keys(<%- importedType %>);
  <%_ }); _%>

  const handleClose = () => {
    navigate('/<%= entityPage %>'<%_ if (paginationPagination) { _%> + location.search<%_ } _%>);
  }

  useEffect(() => {
<%_ if (paginationInfiniteScroll) { _%>
    if (!isNew) {
      dispatch(getEntity(id));
    }
<%_ } else { _%>
    if (isNew) {
      dispatch(reset());
    } else {
      dispatch(getEntity(id));
    }
<%_ } _%>

<%_ otherEntityActions.forEach(val => { _%>
    dispatch(<%= val.action %>({}));
<%_ }) _%>
  }, []);

  useEffect(() => {
    if (updateSuccess) {
      handleClose();
    }
  }, [updateSuccess]);

  const saveEntity = values => {
<%_ for (field of fields) {
    const fieldName = field.fieldName;
_%>
  <%_ if (field.fieldTypeTimed)  { _%>
    values.<%= fieldName %> = convertDateTimeToServer(values.<%= fieldName %>);
  <%_ } else if (field.fieldTypeNumeric) { _%>
    if (values.<%= fieldName %> !== undefined && typeof values.<%= fieldName %> !== 'number') {
      values.<%= fieldName %> = Number(values.<%= fieldName %>);
    }
  <%_ } _%>
<%_ } _%>

    const entity = {
      ...<%= entityInstance %>Entity,
      ...values,
<%_ for (const rel of persistableRelationships.filter(rel => !rel.otherEntity.embedded)) { _%>
  <%_ if (rel.collection) { _%>
      <%= rel.propertyName %>: mapIdList(values.<%= rel.propertyName %>),
  <%_ } else { _%>
      <%= rel.propertyName %>: <%= rel.otherEntity.entityInstancePlural %>.find(it => it.<%= rel.otherEntity.primaryKey.name %>.toString() === values.<%= rel.propertyName %>?.toString()),
  <%_ } _%>
<%_ } _%>
    }

    if (isNew) {
      dispatch(createEntity(entity));
    } else {
      dispatch(updateEntity(entity));
    }
  }


  const defaultValues = () =>
    isNew
      ? {
<%_ for (field of fields.filter(field => !field.id)) {
    const fieldName = field.fieldName;

    if (field.fieldTypeTimed) { _%>
          <%= fieldName %>: displayDefaultDateTime(),
    <%_ } _%>
<%_ } _%>
        }
      : {
<%_ for (field of fields.filter(field => !field.id)) {
    const fieldName = field.fieldName;
  if (field.fieldIsEnum) {
    const enumValues = field.enumValues;_%>
<%= fieldName %>: '<%= enumValues[0].name %>',
  <%_ } _%>
<%_ } _%>
          ...<%= entityInstance %>Entity,
<%_ for (field of fields.filter(field => !field.id)) {
    const fieldName = field.fieldName;
  if (field.fieldTypeTimed) { _%>
          <%= fieldName %>: convertDateTimeFromServer(<%= entityInstance %>Entity.<%= fieldName %>),
  <%_ } _%>
<%_ } _%>
<%_ for (const rel of persistableRelationships.filter(rel => !rel.otherEntity.embedded)) {
    const otherEntityPkName = rel.otherEntity.primaryKey && rel.otherEntity.primaryKey.name || 'id';
    const relationshipFieldName = rel.relationshipFieldName;
    const relationshipFieldNamePlural = rel.relationshipFieldNamePlural;
  if (!rel.collection) { _%>
          <%= relationshipFieldName %>: <%= entityInstance %>Entity?.<%= relationshipFieldName %>?.<%= otherEntityPkName %>,
  <%_ } else { _%>
          <%= relationshipFieldNamePlural %>: <%= entityInstance %>Entity?.<%= relationshipFieldNamePlural %>?.map(e => e.<%= otherEntityPkName %>.toString()),
  <%_ } _%>
<%_ } _%>
        };

  return (
    <div>
    <a-row className="justify-content-center">
      <a-col md="8">
        <h2 id="<%= i18nKeyPrefix %>.home.createOrEditLabel" data-cy="<%= entityClass %>CreateUpdateHeading">
          <Translate contentKey="<%= i18nKeyPrefix %>.home.createOrEditLabel">Create or edit a <%= entityClass %></Translate>
        </h2>
      </a-col>
    </a-row>
    <a-row className="justify-content-center">
      <a-col md="8">
        { loading ? <p>Loading...</p> :
        <ValidatedForm defaultValues={defaultValues()} onSubmit={saveEntity} >
          { !isNew ?
            <ValidatedField
              name="<%= primaryKey.fields[0].fieldName %>" required readOnly
              id="<%= entityFileName %>-<%= primaryKey.fields[0].fieldName %>"
              label={translate('<%= primaryKey.fields[0].fieldTranslationKey %>')}
              validate={{ required: true }}
            />
            : null
          }
<%_ for (field of fields.filter(field => !field.id)) {
    const fieldType = field.fieldType;
    const fieldName = field.fieldName;
    const fieldNameHumanized = field.fieldNameHumanized;

    if (field.fieldTypeBinary && !field.blobContentTypeText) { _%>
          <ValidatedBlobField
  <%_ } else { _%>
          <ValidatedField
  <%_ } _%>
  <%_ if (enableTranslation) { _%>
            label={translate('<%= field.fieldTranslationKey %>')}
  <%_ } else { _%>
            label="<%= fieldNameHumanized %>"
  <%_ } _%>
            id="<%= entityFileName %>-<%= fieldName %>"
            name="<%= fieldName %>"
            data-cy="<%= fieldName %>"
  <%_ if (field.fieldTypeBoolean) { _%>
            check
            type="checkbox"
          />
  <%_ } else if (field.fieldTypeTimed) { _%>
            type="datetime-local"
            placeholder="YYYY-MM-DD HH:mm"
            <%- include('react_validators'); %>
          />
  <%_ } else if (field.fieldTypeLocalDate) { _%>
            type="date"
            <%- include('react_validators'); %>
          />
  <%_ } else if (field.fieldTypeLocalTime) { _%>
            type="time"
            placeholder="HH:mm"
            <%- include('react_validators'); %>
          />
  <%_ } else if (field.fieldIsEnum) {_%>
            type="select"
          >
          <%_ const enumPrefix = frontendAppName + '.'+ fieldType; _%>
          {<%= this._.lowerFirst(fieldType) %>Values.map(<%= this._.lowerFirst(fieldType) %> => (
              <option value={<%= this._.lowerFirst(fieldType) %>} key={<%= this._.lowerFirst(fieldType) %>}>
      <%_ if (enableTranslation) { _%>
                {translate("<%= enumPrefix %>."+<%= this._.lowerFirst(fieldType) %>)}
      <%_ } else { _%>
                {<%= this._.lowerFirst(fieldType) %>}
      <%_ } _%>
              </option>))}
          </ValidatedField>
  <%_ } else if (field.fieldTypeNumeric) { _%>
            type="text"
            <%- include('react_validators'); %>
          />
  <%_ } else if (field.fieldTypeBinary) { _%>
    <%_ if (!field.blobContentTypeText) {  _%>
            <%_ if (field.blobContentTypeImage) {_%>
            isImage accept="image/*"
            <%_ } else { _%>
            openActionLabel={translate('entity.action.open')}
            <%_ } _%>
            <%- include('react_validators'); %>
          />
    <%_ } else { _%>
            type="textarea"
            <%- include('react_validators'); %>
          />
    <%_ } _%>
  <%_ } else { _%>
           type="text"
           <%- include('react_validators'); %>
        />
  <%_ } _%>
  <%_ if (field.documentation) { _%>
          <UncontrolledTooltip target="<%= fieldName %>Label">
    <%_ if (enableTranslation) { _%>
            <Translate contentKey="<%= i18nKeyPrefix %>.help.<%= fieldName %>"/>
    <%_ } else { _%>
            <%= field.documentation %>
    <%_ } _%>
          </UncontrolledTooltip>
  <%_ } _%>
<%_ } _%>
<%_ for (const rel of persistableRelationships.filter(rel => !rel.otherEntity.embedded)) {
    const otherEntityPkName = rel.otherEntity.primaryKey && rel.otherEntity.primaryKey.name || 'id';
    const otherEntityNamePlural = rel.otherEntityNamePlural;
    const relationshipName = rel.relationshipName;
    const relationshipNameHumanized = rel.relationshipNameHumanized;
    const relationshipFieldName = rel.relationshipFieldName;
    const relationshipFieldNamePlural = rel.relationshipFieldNamePlural;
    const otherEntityField = rel.otherEntityField;
    const relationshipRequired = rel.relationshipRequired;
    const translationKey = `${i18nKeyPrefix}.${relationshipName}`; _%>
  <%_ if (!rel.collection) { _%>
          <ValidatedField
            id="<%= entityFileName %>-<%= relationshipName %>"
            name="<%= relationshipFieldName %>"
            data-cy="<%= relationshipFieldName %>"
      <%_ if (enableTranslation) { _%>
            label={translate('<%= translationKey %>')}
      <%_ } else { _%>
            label="<%= relationshipNameHumanized %>"
      <%_ } _%>
            type="select"
      <%_ if (relationshipRequired) { _%>
            required
      <%_ } _%>
          >
              <option value="" key="0" />
              {
                <%= otherEntityNamePlural %> ? <%= otherEntityNamePlural %>.map(otherEntity =>
                  <option
                    value={otherEntity.<%= otherEntityPkName %>}
                    key={otherEntity.<%= otherEntityPkName %>}>
                    {otherEntity.<%= otherEntityField %>}
                  </option>
                ) : null
              }
          </ValidatedField>
    <%_ if (relationshipRequired) { _%>
            <FormText><Translate contentKey="entity.validation.required">This field is required.</Translate></FormText>
    <%_ } _%>
  <%_ } else { _%>
          <ValidatedField
        <%_ if (enableTranslation) { _%>
            label={translate('<%= i18nKeyPrefix %>.<%= relationshipName %>')}
        <%_ } else { _%>
            label="<%= relationshipNameHumanized %>"
        <%_ } _%>
            id="<%= entityFileName %>-<%= relationshipName %>"
            data-cy="<%= relationshipFieldName %>"
            type="select"
            multiple
            name="<%= relationshipFieldNamePlural %>"
            >
              <option value="" key="0" />
              {
                (<%= otherEntityNamePlural %>) ? <%= otherEntityNamePlural %>.map(otherEntity =>
                <option
                    value={otherEntity.<%= otherEntityPkName %>}
                    key={otherEntity.<%= otherEntityPkName %>}>
                    {otherEntity.<%= otherEntityField %>}
                </option>
                ) : null
              }
          </ValidatedField>
  <%_ } _%>
<%_ } _%>
          <Button tag={Link} id="cancel-save" data-cy="entityCreateCancelButton" to="/<%= entityPage %>" replace color="info">
            <FontAwesomeIcon icon="arrow-left" />&nbsp;
            <span className="d-none d-md-inline" ><Translate contentKey="entity.action.back">Back</Translate></span>
          </Button>
          &nbsp;
          <Button color="primary" id="save-entity" data-cy="entityCreateSaveButton" type="submit" disabled={updating}>
            <FontAwesomeIcon icon="save" />&nbsp;
            <Translate contentKey="entity.action.save">Save</Translate>
          </Button>
        </ValidatedForm>
        }
      </a-col>
    </a-row>
  </div>
  );
};

export default <%= entityReactName %>Update;
