package com.ericsson.uecontrol.core.behaviour;

import android.content.Context;
import android.telephony.TelephonyManager;

import com.ericsson.uecontrol.core.UeBehaviour;
import com.ericsson.uecontrol.core.util.CallUtil;
import com.ericsson.uecontrol.gui.MainActivity;
import com.ericsson.uecontrol.core.util.Configurator.Configurable;

import org.apache.log4j.Logger;

/**
 * This behaviour simulates an idle period for the device.
 *
 * Created by ezivkoc on 2014-07-15.
 */
public class UeBehaviourSpeechCall extends UeBehaviour{
    private static final Logger log = Logger.getLogger(UeBehaviourSpeechCall.class);
    public static final int SLEEP_PERIOD = 200;

    @Configurable("Phone Number")
    private String phoneNumber;
    @Configurable("Length(Seconds)")
    private int length;


    public UeBehaviourSpeechCall(){
        this(60);
    }
    public UeBehaviourSpeechCall(int milliseconds){
        length = milliseconds;
    }


    @Override
    protected void execute() throws Exception {
        Context context = MainActivity.getContext();
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

        // Start Call
        log.debug("Starting Call");
        CallUtil.startCall(phoneNumber);
        Thread.sleep(SLEEP_PERIOD);

        // Wait for call to start
        log.debug("Waiting call to start");
        while(tm.getCallState() == TelephonyManager.CALL_STATE_RINGING){
            if(super.stopExecution())
                return;
            super.setProgress(0.2f);
            Thread.sleep(SLEEP_PERIOD);
        }

        // Start timer
        log.debug("Starting call timer");
        int elapsedTime = 0;
        int lengthMillisec = length*1000;
        while(elapsedTime < lengthMillisec){
            if(super.stopExecution())
                return;
            if(tm.getCallState() == TelephonyManager.CALL_STATE_IDLE) {
                log.debug("Call ended prematurely");
                return;
            }
            super.setProgress((float) elapsedTime / lengthMillisec);
            Thread.sleep(SLEEP_PERIOD);
            elapsedTime += SLEEP_PERIOD;
        }

        // End Call
        log.debug("Ending call");
        CallUtil.endCall();
        log.debug("Waiting call to end");
        while(tm.getCallState() != TelephonyManager.CALL_STATE_IDLE){
            if(super.stopExecution())
                return;
            super.setProgress(0.95f);
            Thread.sleep(SLEEP_PERIOD);
        }
    }


    @Override
    public String getName() {
        return "Speech Call";
    }

    @Override
    public String toString() {
        return "Will make a call for "+ length +" seconds";
    }
}
