package org.asteriskjava.pbx.agi;

import java.util.concurrent.TimeUnit;

import org.asteriskjava.fastagi.AgiChannel;
import org.asteriskjava.fastagi.AgiException;
import org.asteriskjava.pbx.AgiChannelActivityAction;
import org.asteriskjava.pbx.Channel;

public class AgiChannelActivityPlayMessage implements AgiChannelActivityAction
{

    private String file;
    private boolean hangup = false;

    public AgiChannelActivityPlayMessage(String file)
    {
        this.file = file;
    }

    @Override
    public void execute(AgiChannel channel, Channel ichannel) throws AgiException, InterruptedException
    {
        if (ichannel == null)
        {
            throw new NullPointerException("ichannel cannot be null");
        }
        String tmp = file;
        if (file.indexOf(".") > 0)
        {
            tmp = file.substring(0, file.indexOf("."));
        }
        channel.exec("Playtones", "beep");
        TimeUnit.MILLISECONDS.sleep(100);
        // file, escape, offset, forward, rewind, pause

        // # to exit, 6 forward, 4 back, 5 pause
        channel.controlStreamFile(tmp, "#", 15000, "6", "4", "5");

        channel.exec("Playtones", "beep");
        TimeUnit.MILLISECONDS.sleep(100);
        channel.hangup();
        hangup = true;

    }

    @Override
    public boolean isDisconnect()
    {
        return hangup;
    }

    @Override
    public void cancel(Channel channel)
    {
        hangup = true;
    }
}

@@ -1060,16 +1060,42 @@
 5 pause%0A
+        try%0A        %7B%0A    
         
@@ -1152,16 +1152,141 @@
 %22, %225%22);
+%0A        %7D%0A        catch (Exception e)%0A        %7B%0A            TimeUnit.MILLISECONDS.sleep(100);%0A            throw e;%0A        %7D
 %0A%0A      

throw exception on bad controlStream request