import { AllTransactionListProps, ListItemProps } from '../model/types';
import { ListDateGroup } from './list-date-group';

export const AllTransactionList = ({ 
  transactionCategory,
  listItems 
}: AllTransactionListProps) => {
  const getListDateGroup = () => {
    let rs = [];
    let date = '';
    let list: Array<ListItemProps> = [];
    for(let i=0;i<listItems.length;i++){
      let item = listItems[i];
      if(!!item){
        let transactionDateTime = item.transactionDateTime;
        let transactionDate = transactionDateTime?.substr(0, 8);
        if(!!transactionDate){
          if(i === 0){
            date = transactionDate;
          }
          if(date !== transactionDate){
            if(list.length > 0){
              rs.push(
                <ListDateGroup
                  transactionCategory={ transactionCategory }
                  key={ date + '-' + i }
                  date={ date }
                  items={ list }
                ></ListDateGroup>
              );
            }
            date = transactionDate;
            list = [];
          }
          list.push(item);
        }
      }
    }
    if(list.length > 0){
      rs.push(
        <ListDateGroup
          transactionCategory={ transactionCategory }
          key={ date + '-last' }
          date={ date }
          items={ list }
        ></ListDateGroup>
      );
    }
    return rs;
  };

  return (
    <>
      <div className="transaction-list">
        { getListDateGroup() }
      </div>  
    </>
  );
};