/*
 * macBeaconTxTimer.java
 *
 * Created on July 9, 2008, 4:20 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package sidnet.stack.mac.ieee802_15_4;

import jist.runtime.JistAPI;
import jist.swans.Constants;
import sidnet.core.misc.TimerInterface;

/**
 *
 * @author Oliver
 * Java adaptation after NS-2 C++ implementation
 */
/*
 * Copyright (c) 2003-2004 Samsung Advanced Institute of Technology and
 * The City University of New York. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the Joint Lab of Samsung 
 *      Advanced Institute of Technology and The City University of New York.
 * 4. Neither the name of Samsung Advanced Institute of Technology nor of 
 *    The City University of New York may be used to endorse or promote 
 *    products derived from this software without specific prior written 
 *    permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE JOINT LAB OF SAMSUNG ADVANCED INSTITUTE
 * OF TECHNOLOGY AND THE CITY UNIVERSITY OF NEW YORK ``AS IS'' AND ANY EXPRESS 
 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN 
 * NO EVENT SHALL SAMSUNG ADVANCED INSTITUTE OR THE CITY UNIVERSITY OF NEW YORK 
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE 
 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT 
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */    
public class macBeaconTxTimer implements TimerInterface
{
     protected boolean started;
    protected boolean busy;
    protected boolean paused;
    protected boolean canceled;
    protected boolean terminated;
    protected double stime = 0.0;		//start time
    protected double wtime = 0.0;		//waiting time
    protected double lastMomentOfPause = 0.0;
    protected double totalPauseTime = 0.0;
    
    
    // ------------------------------------
    private boolean forTX;
    private /* unsigned char*/ byte macBeaconOrder_last;
    private Mac802_15_4Impl	mac;
    
    private TimerInterface self = (TimerInterface)JistAPI.proxy(this, TimerInterface.class);

    public macBeaconTxTimer(Mac802_15_4Impl m) // macBeaconTxTimer(Mac802_15_4Impl *m) : p802_15_4Timer() {macBeaconOrder_last = 15; mac = m;}
    {
        super();
        macBeaconOrder_last = 15;
        mac = m;
    }
    // void start(boolean reset = false, boolean fortx = false, double wt = 0.0); NS-2
    public void start()
    {
        //reset = false;
        forTX = false;
        wtime = 0;
    }
    public void	start(boolean reset, boolean fortx, double wt)
    {
        double wtime;

        if (reset)
        {
                forTX = fortx;
                macBeaconOrder_last = 15;
                if (this.busy())
                        this.stopTimerr();
                this.startTimer(wt);
                return;
        }
        else
        {
                forTX = (!forTX);
        }
        if (!forTX)
                this.startTimer(12 / mac.phy.getRate_BitsPerSecond('s'));
        else if (mac.mpib.macBeaconOrder != 15)
        {
                wtime = ((Const.aBaseSuperframeDuration * (1 << mac.mpib.macBeaconOrder) - 12) / mac.phy.getRate_BitsPerSecond('s'));
                this.startTimer(wtime);
                macBeaconOrder_last = mac.mpib.macBeaconOrder;
        }
        else if (macBeaconOrder_last != 15)
        {
                wtime = ((Const.aBaseSuperframeDuration * (1 << macBeaconOrder_last) - 12) / mac.phy.getRate_BitsPerSecond('s'));
                this.startTimer(wtime);
        }
    }

    public void	timeout()
    {
        resetTimer();
        mac.beaconTxHandler(forTX);
        terminated = true;
    }
    // ------------------------------------
    
      public void resetTimer()
    {
        started    = false;
        busy       = false;
        paused     = false;
        canceled   = false;
        terminated = false;
        stime = 0;
        wtime = 0;
    }
    
    
    
    /**
     * Start timer
     */
    private void startTimer(double time)
    {
        assert(!busy && !started);
	busy = true;
	stime = JistAPI.getTime();
	wtime = time;
	assert(wtime >= 0);
	//s.schedule(this, /* & */event, wtime);
        JistAPI.sleep((long)(wtime * Constants.SECOND));
        if (!canceled && !terminated && !paused)
        {
            self.timeout();
            //terminated = true;
        }
    }
    
    /**
     * Cancel timer
     */ 
    public void cancel()
    {
        assert(started);
        canceled = true;
    }
    
    public boolean canceled()
    {
        return canceled;
    }
    
    public boolean busy()
    {
        return busy;
    }
    
    public boolean paused()
    {
        return paused;
    }
    
    public double expire()
    {
        return ((double)JistAPI.getTime())/Constants.SECOND - stime - totalPauseTime > wtime ? 0 : wtime - (JistAPI.getTime() - stime - totalPauseTime);
    }
   
    /** 
     * Pause timer
     */
    public void pause()
    {
        assert(started && !terminated && !canceled && !paused);
        paused = true;
        lastMomentOfPause = JistAPI.getTime();
    }
    
    /** 
     * Resume timer
     */
    public void resume()
    {
        assert(started && !terminated && !canceled);
        totalPauseTime += JistAPI.getTime() - lastMomentOfPause;
        paused = false;
        // sleep for the remaining amount of time in the timer
        JistAPI.sleepBlock((long)(expire() * Constants.SECOND));
        if (!canceled && !terminated && !paused)
        {
            self.timeout();
            //terminated = true;
        }            
    }
    
    public void stopTimerr()
    {
         cancel();
	 resetTimer();
    }
}
