/* JFox, the OpenSource J2EE Application Server
 *
 * Distributable under GNU LGPL license by gun.org
 * more details please visit http://www.huihoo.org/jfox
 */

package org.jfox.jms;

import java.util.ArrayList;
import java.util.List;

import org.jfox.jms.message.JMSMessage;

/**
 * the actual message sender
 * start a new thread to send messages with one session
 *
 * @author <a href="mailto:young_yy@hotmail.com">Young Yang</a>
 */

class JMSSender {

    // new messages
    private List newMessages = new ArrayList();

    // messages sent, wait for acknowledge
    private List unAckMessages = new ArrayList();

    private JMSSession session = null;
    private JMSConnection conn = null;

    public JMSSender(JMSSession session) {
        this.session = session;
        conn = session.getJMSConnection();
    }

    public void sendMessage(JMSMessage msg){
        unAckMessages.add(msg);
    }

    /**
     * start send and ack thread
     */
    public void start(){
        new SendThread().start();
        new AckThread().start();
    }

    private class SendThread extends Thread {

        public void run() {
            while(true) {
                while(!newMessages.isEmpty()) {
                    JMSMessage msg = (JMSMessage) newMessages.remove(0);
                    try {
                        conn.sendMessage(msg.getJMSDestination(), msg, msg.getJMSDeliveryMode(), msg.getJMSPriority(), msg.getJMSExpiration());
                        unAckMessages.add(msg);
                    }
                    catch(Exception e) {
                        e.printStackTrace();
                    }
                }

                synchronized(this) {
                    try {
                        wait();
                    }
                    catch(Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    private class AckThread extends Thread {
        public void run() {
            while(true){
                while(!unAckMessages.isEmpty()){
                    //TODO check unAck message
                }
                synchronized(this) {
                    try {
                        wait(session.getAckTimeout());
                    }
                    catch(Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    /**
     * check the message unack, may resend or drop it
     */
    private void checkAckMsgs() {

    }


    public static void main(String[] args) {

    }
}
