package com.tibbo.aggregate.common.datatable;

import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class DataTableSorter implements Iterable<SortOrder>
{
  public static final DataTableSorter EMPTY_SORTER = new DataTableSorter(Collections.emptyList());

  private final List<SortOrder> orders = new LinkedList();

  public DataTableSorter(SortOrder... orders)
  {
    this.orders.addAll(Arrays.asList(orders));
  }

  public DataTableSorter(List<SortOrder> orders)
  {
    this.orders.addAll(orders);
  }

  public boolean isEmpty()
  {
    return orders.isEmpty();
  }

  public List<SortOrder> getOrders()
  {
    return orders;
  }

  public void addOrder(SortOrder order)
  {
    orders.add(order);
  }

  @Override
  public Iterator<SortOrder> iterator()
  {
    return orders.iterator();
  }

  public DataTableSorter fitTo(TableFormat format)
  {
    List<SortOrder> newOrders = null;
    int startIndex = 0;
    int endIndex = 0;
    boolean foundCommonFields = false;

    for (SortOrder order : orders)
    {
      if (format.hasField(order.getField()))
      {
        ++endIndex;
        foundCommonFields = true;
        continue;
      }

      if (!foundCommonFields)
      {
        continue;
      }

      if (newOrders == null)
      {
        newOrders = new LinkedList();
      }

      newOrders.addAll(orders.subList(startIndex, endIndex));
      startIndex = ++endIndex;
    }

    if (newOrders != null)
    {
      return new DataTableSorter(newOrders);
    }

    return foundCommonFields ? this : EMPTY_SORTER;
  }
  
}
