<%#
 Copyright 2013-2021 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';
<%_ if (pagination === 'infinite-scroll') { _%>
import InfiniteScroll from 'react-infinite-scroller';
<%_ } _%>
import { connect } from 'react-redux';
import { Link, RouteComponentProps } from 'react-router-dom';
import { Button, <% if (searchEngine !== false) { %>InputGroup, <% } %>Col, Row, Table } from 'reactstrap';
<%_ if (searchEngine !== false) { _%>
import { AvForm, AvGroup, AvInput } from 'availity-reactstrap-validation';
<%_ } _%>
import {
  <%_ if (blobFields.length > 0) { _%>
    <%_ if (fieldsContainBlobOrImage) { _%>
  openFile,
    <%_ } _%>
  byteSize,
  <%_ } _%>
  Translate<% if (searchEngine !== false) { %>, translate, ICrudSearchAction<% } %>
  <% if (fieldsContainDate) { %>, TextFormat<% } %>
  <%_ if (pagination !== 'no') { _%>
  , getSortState, IPaginationBaseState
  <%_ if (pagination === 'pagination' || pagination === 'pager') { _%>
  , JhiPagination, JhiItemCount
  <%_ }} _%>
} from 'react-jhipster';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';

<%_ if (fieldsContainDuration) { _%>
import { DurationFormat } from 'app/shared/DurationFormat';
<%_ } _%>

import { IRootState } from 'app/shared/reducers';
import {
  <%_ if (searchEngine !== false) { _%>
  getSearchEntities,
  <%_ } _%>
  getEntities
  <%_ if (pagination === 'infinite-scroll') { _%>
  , reset
  <%_ } _%>
} from './<%= entityFileName %>.reducer';
import { I<%= entityReactName %> } from 'app/shared/model/<%= entityModelFileName %>.model';
import { APP_DATE_FORMAT, APP_LOCAL_DATE_FORMAT } from 'app/config/constants';
<%_ if (pagination !== 'no') { _%>
import { ITEMS_PER_PAGE } from 'app/shared/util/pagination.constants';
import { overridePaginationStateWithQueryParams } from 'app/shared/util/entity-utils';
<%_ } _%>

export interface I<%= entityReactName %>Props extends StateProps, DispatchProps, RouteComponentProps<{url: string}> {}

export const <%= entityReactName %> = (props: I<%= entityReactName %>Props) => {
  <%_ if (searchEngine !== false || pagination !== 'no') { _%>
    <%_ if (searchEngine !== false) { _%>
  const [search, setSearch] = useState('');
    <%_ } _%>
    <%_ if (pagination !== 'no') { _%>
  const [paginationState, setPaginationState] = useState(overridePaginationStateWithQueryParams(getSortState(props.location, ITEMS_PER_PAGE, '<%= primaryKey.name %>'), props.location.search));
    <%_ } _%>
  <%_ } _%>
  <%_ if (pagination === 'infinite-scroll') { _%>
  const [sorting, setSorting] = useState(false);
  <%_ } _%>

  <%_ if (pagination === 'pagination' || pagination === 'infinite-scroll' || pagination !== 'no' && pagination !== 'infinite-scroll') { _%>
  const getAllEntities = () => {
    <%_ if (searchEngine !== false) { _%>
    if (search) {
      props.getSearchEntities(search, paginationState.activePage - 1, paginationState.itemsPerPage, `${paginationState.sort},${paginationState.order}`);
    } else {
      props.getEntities(paginationState.activePage - 1, paginationState.itemsPerPage, `${paginationState.sort},${paginationState.order}`);
    }
    <%_ } else { _%>
    props.getEntities(paginationState.activePage - 1, paginationState.itemsPerPage, `${paginationState.sort},${paginationState.order}`);
    <%_ } _%>
  };
  <%_ } _%>

  <%_ if (pagination === 'infinite-scroll') { _%>
  const resetAll = () => {
    props.reset();
    setPaginationState({
      ...paginationState,
      activePage: 1
    });
    props.getEntities();
  };
  <%_ } _%>

  <%_ if (pagination === 'no' || pagination === 'infinite-scroll') { _%>
  useEffect(() => {
    <%_ if (pagination !== 'no') { _%>
    resetAll();
    <%_ } else { _%>
    props.getEntities();
    <%_ } _%>
  }, []);
  <%_ } _%>

  <%_ if (searchEngine !== false) { _%>
  const startSearching = () => {
    if (search) {
      <%_ if (pagination === 'infinite-scroll') { _%>
      props.reset();
      <%_ } _%>
      <%_ if (pagination !== 'no') { _%>
      setPaginationState({
        ...paginationState,
        activePage: 1
      });
      props.getSearchEntities(search, paginationState.activePage - 1, paginationState.itemsPerPage, `${paginationState.sort},${paginationState.order}`);
      <%_ } else { _%>
      props.getSearchEntities(search);
      <%_ } _%>
    }
  };

  const clear = () => {
    <%_ if (pagination === 'infinite-scroll') { _%>
    props.reset();
    <%_ } _%>
    setSearch('');
    <%_ if (pagination !== 'no') { _%>
    setPaginationState({
      ...paginationState,
      activePage: 1
    });
    <%_ } _%>
    props.getEntities();
  };

  const handleSearch = event => setSearch(event.target.value);
  <%_ } _%>

  <%_ if (pagination === 'infinite-scroll') { _%>
  useEffect(() => {
    if (props.updateSuccess) {
      resetAll();
    }
  }, [props.updateSuccess]);

  useEffect(() => {
    getAllEntities()
  }, [paginationState.activePage]);

  const handleLoadMore = () => {
    if ((window as any).pageYOffset > 0) {
      setPaginationState({
        ...paginationState,
        activePage: paginationState.activePage + 1
      });
    }
  };
  <%_ } _%>

  <%_ if (pagination !== 'no') { _%>

  <%_ if (pagination === 'pagination') { _%>
  const sortEntities = () => {
    getAllEntities();
    const endURL = `?page=${paginationState.activePage}&sort=${paginationState.sort},${paginationState.order}`;
    if (props.location.search !== endURL) {
      props.history.push(`${props.location.pathname}${endURL}`);
    }
  };
  <%_ } _%>

  useEffect(() => {
    <% if (pagination === 'infinite-scroll') { %>
    if (sorting) {
      getAllEntities();
      setSorting(false);
    }
    <% } else { %>
    sortEntities();
    <% } %>
  }, [<% if (pagination === 'infinite-scroll') { %>sorting<% } else { %>paginationState.activePage, paginationState.order, paginationState.sort<% } %><%_ if (searchEngine !== false) { _%>, search<% } %>]);

  <%_ if (pagination === 'pagination') { _%>
  useEffect(() => {
    const params = new URLSearchParams(props.location.search);
    const page = params.get('page');
    const sort = params.get('sort');
    if (page && sort) {
      const sortSplit = sort.split(',');
      setPaginationState({
        ...paginationState,
        activePage: +page,
        sort: sortSplit[0],
        order: sortSplit[1]
      });
    }
  }, [props.location.search]);
  <%_ } _%>

  const sort = p => () => {
    <% if (pagination === 'infinite-scroll') { %>
    props.reset();
    setPaginationState({
      ...paginationState,
      activePage: 1,
      order: paginationState.order === 'asc' ? 'desc' : 'asc',
      sort: p
    });
    setSorting(true);
    <% } else { %>
    setPaginationState({
      ...paginationState,
      order: paginationState.order === 'asc' ? 'desc' : 'asc',
      sort: p
    });
    <% } %>
  };

  <%_ if (pagination === 'pagination') { _%>
  const handlePagination = currentPage =>
    setPaginationState({
      ...paginationState,
      activePage: currentPage
    });
  <%_ } _%>
  <%_ } _%>

  const handleSyncList = () => {
    <% if (pagination === 'no') { %>
      props.getEntities();
    <% } %>
    <% if (pagination === 'pagination') { %>
      sortEntities();
    <% } %>
    <% if (pagination === 'infinite-scroll') { %>
      resetAll();
    <% } %>
  };

  const { <%= entityInstance %>List, match, loading<% if (pagination === 'pagination') { %>, totalItems<% } %>} = props;
  return (
    <div>
      <h2 id="<%= entityFileName %>-heading" data-cy="<%= entityClass %>Heading">
        <Translate contentKey="<%= i18nKeyPrefix %>.home.title"><%= entityClassPluralHumanized %></Translate>
        <div className="d-flex justify-content-end">
          <Button className="mr-2" color="info" onClick={handleSyncList} disabled={loading}>
            <FontAwesomeIcon icon="sync" spin={loading} /> <Translate contentKey="<%= i18nKeyPrefix %>.home.refreshListLabel">Refresh List</Translate>
          </Button>
          <%_ if (!readOnly) { _%>
            <Link to={`${match.url}/new`} className="btn btn-primary jh-create-entity" id="jh-create-entity" data-cy="entityCreateButton">
              <FontAwesomeIcon icon="plus" />&nbsp;
              <Translate contentKey="<%= i18nKeyPrefix %>.home.createLabel">
                Create new <%= entityClassHumanized %>
              </Translate>
            </Link>
          <%_ } _%>
        </div>
      </h2>
      <%_ if (searchEngine !== false) { _%>
      <Row>
        <Col sm="12">
          <AvForm onSubmit={startSearching}>
            <AvGroup>
              <InputGroup>
                <AvInput type="text" name="search" value={search} onChange={handleSearch}
                  placeholder=<% if (enableTranslation) { %>{translate('<%= i18nKeyPrefix %>.home.search')}<% } else { %>"Search"<% } %>/>
                <Button className="input-group-addon">
                  <FontAwesomeIcon icon="search" />
                </Button>
                <Button type="reset" className="input-group-addon" onClick={clear}>
                  <FontAwesomeIcon icon="trash" />
                </Button>
              </InputGroup>
            </AvGroup>
          </AvForm>
        </Col>
      </Row>
      <%_ } _%>
      <div className="table-responsive">
        <%_ if (pagination === 'infinite-scroll') { _%>
        <InfiniteScroll pageStart={paginationState.activePage}
                        loadMore={handleLoadMore}
                        hasMore={paginationState.activePage - 1 < props.links.next}
                        loader={<div className="loader">Loading ...</div>}
                        threshold={0}
                        initialLoad={false}>
        <%_ } _%>
        {
          <%= entityInstance %>List && <%= entityInstance %>List.length > 0 ?(
            <Table responsive>
              <thead>
                <tr>
                  <%_ for (field of fields) { _%>
                  <th<% if (pagination !== 'no') { %> className="hand" onClick={sort('<%= field.fieldName %>')} <%_ } _%>><Translate contentKey="<%= `${i18nKeyPrefix}.${field.fieldName}` %>"><%= field.fieldNameHumanized %></Translate><% if (pagination !== 'no') { %> <FontAwesomeIcon icon="sort" /><% } %></th>
                  <%_ } _%>
                  <%_ for (relationship of relationships) { _%>
                      <%_ if (relationship.relationshipType === 'many-to-one'
                      || (relationship.relationshipType === 'one-to-one' && relationship.ownerSide === true)
                      || (relationship.relationshipType === 'many-to-many' && relationship.ownerSide === true && pagination === 'no')) {
                      const fieldName = "." + relationship.otherEntityField; _%>
                  <th<% if (pagination !== 'no') { %> <% } %>><Translate contentKey="<%= `${i18nKeyPrefix}.${relationship.relationshipName}` %>"><%= relationship.relationshipNameHumanized %></Translate><% if (pagination !== 'no') { %> <FontAwesomeIcon icon="sort" /><% } %></th>
                      <%_ } _%>
                  <%_ } _%>
                  <th />
                </tr>
              </thead>
              <tbody>
                {
                  <%= entityInstance %>List.map((<%= entityInstance %>, i) => (
                  <tr key={`entity-${i}`} data-cy="entityTable">
                    <td>
                      <Button tag={Link} to={`${match.url}/${<%= entityInstance %>.<%= primaryKey.name %>}`} color="link" size="sm">
                        {<%= entityInstance %>.<%= primaryKey.name %>}
                      </Button>
                    </td>
                    <%_ for (field of fields) {
                      const fieldType = field.fieldType;
                      const fieldName = field.fieldName;
                      const fieldIsEnum = field.fieldIsEnum;
                    _%>
                    <%_ if (fieldName !== primaryKey.name) { _%>
                    <td>
                    <%_ if (fieldType === 'Boolean') { _%>
                      {<%= entityInstance %>.<%= field.fieldName %> ? 'true' : 'false'}
                    <%_ } else if (fieldType === 'Instant' || fieldType === 'ZonedDateTime') { _%>
                      {<%= entityInstance %>.<%= fieldName %> ? <TextFormat type="date" value={<%= entityInstance %>.<%= fieldName %>} format={APP_DATE_FORMAT} />: null}
                    <%_ } else if (fieldType === 'Duration') { _%>
                      {<%= entityInstance %>.<%= fieldName %> ? <DurationFormat value={<%= entityInstance %>.<%= fieldName %>} />: null}
                    <%_ } else if (fieldType === 'LocalDate') { _%>
                      {<%= entityInstance %>.<%= fieldName %> ? <TextFormat type="date" value={<%= entityInstance %>.<%= fieldName %>} format={APP_LOCAL_DATE_FORMAT} />: null}
                    <%_ } else if (fieldIsEnum && enableTranslation) { _%>
                      <Translate contentKey={`<%= frontendAppName %>.<%= fieldType %>.${<%= entityInstance %>.<%= fieldName %>}`} />
                    <%_ } else if (['byte[]', 'ByteBuffer'].includes(fieldType)) { _%>
                      <%_
                        // blobFields
                        const fieldBlobType = field.fieldTypeBlobContent;
                        if (fieldBlobType !== 'text') {
                      _%>
                        {<%= entityInstance %>.<%= fieldName %> ? (
                          <div>
                            {<%= entityInstance %>.<%= fieldName %>ContentType ? (
                              <a onClick={openFile(<%= entityInstance %>.<%= fieldName %>ContentType, <%= entityInstance %>.<%= fieldName %>)}>
                                <%_ if (fieldBlobType === 'image') { _%>
                                  <img src={`data:${<%= entityInstance %>.<%= fieldName %>ContentType};base64,${<%= entityInstance %>.<%= fieldName %>}`} style={{ maxHeight: '30px' }} />
                                <%_ } else { _%>
                                  <Translate contentKey="entity.action.open">Open</Translate>
                                <%_ } _%>
                                &nbsp;
                              </a>
                            ) : null}
                            <span>{<%= entityInstance %>.<%= fieldName %>ContentType}, {byteSize(<%= entityInstance %>.<%= fieldName %>)}</span>
                          </div>
                        ) : null}
                      <%_ } else { _%>
                          {<%= entityInstance %>.<%= fieldName %>}
                      <%_ } _%>
                    <%_ } else { _%>
                      {<%= entityInstance %>.<%= fieldName %>}
                    <%_ } _%>
                    </td>
                    <%_ } _%>
                    <%_ } _%>
                    <%_ for (relationship of relationships) {
                      const relationshipType = relationship.relationshipType;
                      const ownerSide = relationship.ownerSide;
                      const relationshipFieldName = relationship.relationshipFieldName;
                      const relationshipFieldNamePlural = relationship.relationshipFieldNamePlural;
                      const otherEntityName = relationship.otherEntityName;
                      const otherEntityPkName = relationship.otherEntity.primaryKey && relationship.otherEntity.primaryKey.name || 'id';
                      const otherEntityStateName = relationship.otherEntityStateName;
                      const otherEntityField = relationship.otherEntityField;
                      const otherEntityFieldCapitalized = relationship.otherEntityFieldCapitalized; _%>
                      <%_ if (relationshipType === 'many-to-one'
                      || (relationshipType === 'one-to-one' && ownerSide === true)
                      || (relationshipType === 'many-to-many' && ownerSide === true && pagination === 'no')) { _%>
                    <td>
                      <%_ if (otherEntityName === 'user') { _%>
                        <%_ if (relationshipType === 'many-to-many') { _%>
                      {
                        (<%= entityInstance %>.<%= relationshipFieldNamePlural %>) ?
                            (<%= entityInstance %>.<%= relationshipFieldNamePlural %>.map((val, j) =>
                                <span key={j}>{val.<%= otherEntityField %>}{(j === <%= entityInstance %>.<%= relationshipFieldNamePlural %>.length - 1) ? '' : ', '}</span>
                            )
                        ) : null
                      }
                        <%_ } else { _%>
                      {<%= entityInstance + "." + relationshipFieldName %> ? <%= entityInstance + "." + relationshipFieldName + "." + otherEntityField %> : ''}
                        <%_ } _%>
                        <%_ } else { _%>
                          <%_ if (relationshipType === 'many-to-many') { _%>
                        {
                          (<%= entityInstance %>.<%= relationshipFieldNamePlural %>) ?
                              (<%= entityInstance %>.<%= relationshipFieldNamePlural %>.map((val, j) =>
                                  <span key={j}><Link to={`<%= otherEntityStateName %>/${val.id}`}>{val.<%= otherEntityField %>}</Link>{(j === <%= entityInstance %>.<%= relationshipFieldNamePlural %>.length - 1) ? '' : ', '}</span>
                              )
                          ) : null
                        }
                          <%_ } else { _%>
                        {<%= entityInstance + "." + relationshipFieldName %> ?
                        <Link to={`<%= otherEntityStateName %>/${<%= entityInstance + "." + relationshipFieldName + "." + otherEntityPkName + "}" %>`}>
                          {<%= entityInstance + "." + relationshipFieldName + "." + otherEntityField %>}
                        </Link> : ''}
                          <%_ } _%>
                        <%_ } _%>
                      </td>
                      <%_ } _%>
                      <%_ } _%>
                      <td className="text-right">
                        <div className="btn-group flex-btn-group-container">
                          <Button tag={Link} to={`${match.url}/${<%= entityInstance %>.<%= primaryKey.name %>}`} color="info" size="sm" data-cy="entityDetailsButton">
                            <FontAwesomeIcon icon="eye" /> <span className="d-none d-md-inline" ><Translate contentKey="entity.action.view">View</Translate></span>
                          </Button>
                          <%_ if (!readOnly) { _%>
                          <Button tag={Link} to={`${match.url}/${<%= entityInstance %>.<%= primaryKey.name %>}/edit<%_ if (pagination === 'pagination') { _%>?page=${paginationState.activePage}&sort=${paginationState.sort},${paginationState.order}<%_ } _%>`} color="primary" size="sm" data-cy="entityEditButton">
                            <FontAwesomeIcon icon="pencil-alt" /> <span className="d-none d-md-inline"><Translate contentKey="entity.action.edit">Edit</Translate></span>
                          </Button>
                          <Button tag={Link} to={`${match.url}/${<%= entityInstance %>.<%= primaryKey.name %>}/delete<%_ if (pagination === 'pagination') { _%>?page=${paginationState.activePage}&sort=${paginationState.sort},${paginationState.order}<%_ } _%>`} color="danger" size="sm" data-cy="entityDeleteButton">
                            <FontAwesomeIcon icon="trash" /> <span className="d-none d-md-inline"><Translate contentKey="entity.action.delete">Delete</Translate></span>
                          </Button>
                          <%_ } _%>
                        </div>
                      </td>
                    </tr>
                  ))
                }
              </tbody>
            </Table>
          ) : (
              !loading && <div className="alert alert-warning">
              <Translate contentKey="<%= i18nKeyPrefix %>.home.notFound">
                No <%= entityClassPluralHumanized %> found
              </Translate>
            </div>
          )
        }
        <%_ if (pagination === 'infinite-scroll') { _%>
        </InfiniteScroll>
        <%_ } _%>
      </div>
      <%_ if (databaseType !== 'cassandra') { _%>
        <%_ if (pagination === 'pagination') { _%>
        { props.totalItems ? (<div className={ <%= entityInstance %>List && <%= entityInstance %>List.length > 0 ? '' : 'd-none' }>
          <Row className="justify-content-center">
            <JhiItemCount
              page={paginationState.activePage}
              total={totalItems}
              itemsPerPage={paginationState.itemsPerPage}
              <% { if (enableTranslation) { %>i18nEnabled<% }} %>
            />
          </Row>
          <Row className="justify-content-center">
            <JhiPagination
              activePage={paginationState.activePage}
              onSelect={handlePagination}
              maxButtons={5}
              itemsPerPage={paginationState.itemsPerPage}
              totalItems={props.totalItems}
            />
          </Row>
        </div>) : '' }
        <% } _%>
      <%_ } _%>
    </div>
  );
};

const mapStateToProps = ({ <%= entityInstance %> }: IRootState) => ({
  <%= entityInstance %>List: <%= entityInstance %>.entities,
  loading: <%= entityInstance %>.loading,
  <%_ if (pagination !== 'no') { _%>
  totalItems: <%= entityInstance %>.totalItems,
  <%_ } _%>
  <%_ if (pagination === 'infinite-scroll') { _%>
  links: <%= entityInstance %>.links,
  entity: <%= entityInstance %>.entity,
  updateSuccess: <%= entityInstance %>.updateSuccess,
  <%_ } _%>
});

const mapDispatchToProps = {
 <%_ if (searchEngine !== false) { _%>
 getSearchEntities,
 <%_ } _%>
 getEntities,
 <%_ if (pagination === 'infinite-scroll') { _%>
 reset
 <%_ } _%>
};

type StateProps = ReturnType<typeof mapStateToProps>;
type DispatchProps = typeof mapDispatchToProps;

export default connect(mapStateToProps, mapDispatchToProps)(<%= entityReactName %>);
