/*******************************************************************************
 * Copyright (c), 2001, 2002 N2 Broadband, Inc.  All Rights Reserved.
 *
 * This module contains unpublished, confidential, proprietary
 * material.  The use and dissemination of this material are
 * governed by a license.  The above copyright notice does not
 * evidence any actual or intended publication of this material.
 *
 * Author:  Drake H. Henderson
 * Created:  11-12-01
 *
 ******************************************************************************/

package com.n2bb.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.n2bb.util.N2bbSettings;

public class ScrollUtil {
  
  private static Log n2bbLog = LogFactory.getLog(N2bbSettings.N2BB_LOG);

  public static int getStartRecord(int requestedStart, int pageSize, int numberOfRecords) {
    try {
      int start = 1;

      if (requestedStart > numberOfRecords)
        requestedStart = numberOfRecords;

      int fullPages = (requestedStart / pageSize);
      start = (fullPages * pageSize) + 1;

      // no partial pages
      if ((fullPages * pageSize) == numberOfRecords) 
        start = start - pageSize;      

      // possible if user enters negative goto page
      if (start <= 0)
        start = 1;
          
      return start;
      
    } catch (Exception e) {
      n2bbLog.error("exception - message... " + e.getMessage(), e);
      return 1;
    }
  }

  public static Integer calcScroll(String gotoPage, String prevNextRecStart, int numberOfRecords) {
    n2bbLog.debug("enter");
    
    int pageSize = N2bbSettings.PAGE_SIZE;
    
    try {
      // goto page was entered
      if (gotoPage != null && !gotoPage.trim().equals("")) {
        n2bbLog.debug("gotoPage... " + gotoPage);

        int gotoPageInt = 1;
        try { 
          gotoPageInt = Integer.parseInt(gotoPage);
        } catch (Exception e) {}
        if (gotoPageInt <= 0) {
          gotoPageInt = 1;
        }

        int gotoRec = (gotoPageInt * pageSize) - (pageSize - 1);
        n2bbLog.debug("gotoRec (calculated)... " + gotoRec);
        
        gotoRec = getStartRecord(gotoRec, pageSize, numberOfRecords);
        n2bbLog.debug("gotoRec (final)... " + gotoRec);
        
        return new Integer(gotoRec);
        
      // prev next link clicked        
      } else {
        n2bbLog.debug("prev next");
        
        int prevNextInt = 1;
        try {
          prevNextInt = Integer.parseInt(prevNextRecStart);
        } catch (Exception e) {}
        
        return new Integer(prevNextInt);
        
      }
      
    } catch (Exception e) {
      n2bbLog.error("exception - message... " + e.getMessage(), e);
      return new Integer(1);
    }
    
  }
  
}
