/*
 * $Id: ConverterTiming.java,v 1.9 2007/08/16 11:10:56 marbobo Exp $
 *
 * Copyright (c) Siemens AG 2008 
 *           (c) Universität Paderborn 2008 
 * Licensed under EUPL 1.1. 
 *
 * $Log: ConverterTiming.java,v $
 * Revision 1.9  2007/08/16 11:10:56  marbobo
 * + Bugfixes
 * + Refactorings
 *
 * Revision 1.8  2004/12/10 21:39:18  marbobo
 * + Anpassungen wegen Umstellung auf PreparedStatement
 *
 */
package vkc.db.common;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Time;
import java.util.Calendar;

import vkc.db.helper.DBHelper;
import vkc.exception.DBException;

/**
 * This class represents some useful information aboutthe time frame of a
 * converter server.
 * 
 * @created 07.01.2004
 * @author Andreas Koop
 */
public class ConverterTiming extends PersistentObject {
    private long pollingPeriodMillis;

    private Calendar calendar = Calendar.getInstance();

    private Time timeFrameStart;

    private Time timeFrameEnd;

    /**
     * Construtcs a new ConverterTiming object corresponding to
     * <code>CONVERTERTIMING</code> table.
     */
    public ConverterTiming() {
        super("CONVERTERTIMING", "ID");
    }

    public long getPollingPeriodMillis() {
        return pollingPeriodMillis;
    }

    public Time getTimeFrameEnd() {
        return timeFrameEnd;
    }

    public Time getTimeFrameStart() {
        return timeFrameStart;
    }

    public void setPollingPeriodMinutes(long minutes) {
        pollingPeriodMillis = minutes * 60L * 1000L;
    }

    public void setTimeFrameEnd(String time) {
        timeFrameEnd = getTime(time);
    }

    public void setTimeFrameStart(String time) {
        timeFrameStart = getTime(time);
    }

    /**
     * Checks whether we are in the time frame at this very moment.
     * 
     * @return true, if so. false otherwise.
     */
    public boolean inTimeFrame() {
        int now = getSecondsOfDay(System.currentTimeMillis());
        int start = getSecondsOfDay(timeFrameStart.getTime());
        int end = getSecondsOfDay(timeFrameEnd.getTime());

        if (end < start) {
            // Move all times so that timeFrameEnd is 23:59:59
            int offset = end + 1;
            end = 86399;
            start -= offset;
            now -= offset;

            if (now < 0) {
                now += 86400;
            }
        }

        return now > start && now < end;
    }

    /**
     * Parses and returns the corresponding time object for a String of the form
     * "hh:mm"
     * 
     * @param time
     *            e.g. "14:34"
     * @return
     */
    private Time getTime(String time) {
        String[] hm = time.split(":");

        // Cuts the leading zeros
        for (int i = 0; i < hm.length; i++) {
            if (hm[i].charAt(0) == '0' && hm[i].length() == 2 && hm[i].charAt(1) != '0') {
                hm[i] = hm[i].substring(1);
            }
        }

        calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hm[0]));
        calendar.set(Calendar.MINUTE, Integer.parseInt(hm[1]));
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);

        return new Time(calendar.getTimeInMillis());
    }

    /**
     * Returns the number of seconds by day
     * 
     * @param millis
     * @return
     */
    private int getSecondsOfDay(long millis) {
        calendar.setTimeInMillis(millis);

        return calendar.get(Calendar.HOUR_OF_DAY) * 3600 + calendar.get(Calendar.MINUTE) * 60 + calendar.get(Calendar.SECOND);
    }

    /**
     * (non-Javadoc)
     * 
     * @see java.lang.Object#toString()
     */
    public String toString() {
        return timeFrameStart + "-" + timeFrameEnd;
    }

    /**
     * (non-Javadoc)
     * 
     * @see vkc.db.common.PersistentObject#initialize(java.lang.Integer,
     *      java.sql.Connection)
     */
    public void initialize(Integer id, Connection conn) throws DBException {
        PreparedStatement pStmt = null;
        ResultSet rs = null;

        try {
            pStmt = conn.prepareStatement("SELECT * FROM CONVERTERTIMING WHERE ID = ?");
            pStmt.setInt(1, id.intValue());
            rs = pStmt.executeQuery();

            if (rs.next()) {
                setId(id);
                setPollingPeriodMinutes(rs.getInt("POLLING_PERIOD_MINUTES"));
                setTimeFrameStart(rs.getString("TIME_FRAME_START"));
                setTimeFrameEnd(rs.getString("TIME_FRAME_END"));
            } else {
                throw new DBException("CONVERTERTIMING for id = " + id + " not found!");
            }
        } catch (Exception e) {
            throw new DBException(e);
        } finally {
            DBHelper.close(rs);
            DBHelper.close(pStmt);
        }
    }
}