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 org.apache.log4j.Logger;

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



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

        // Wait to receive Call
        log.debug("Waiting for call...");
        while(tm.getCallState() != TelephonyManager.CALL_STATE_RINGING ){
            if(super.stopExecution())
                return;
            super.setProgress(0.2f);
            Thread.sleep(SLEEP_PERIOD);
        }
        log.debug("Phone is ringing, answering call");
        Thread.sleep(1000);
        CallUtil.answerCall();

        // Wait for call to end
        log.debug("Waiting for call to end...");
        while(tm.getCallState() != TelephonyManager.CALL_STATE_IDLE){
            if(super.stopExecution())
                return;
            super.setProgress(0.6f);
            Thread.sleep(SLEEP_PERIOD);
        }
        log.debug("Call has ended");
    }


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

    @Override
    public String toString() {
        return "Will wait for a call and then answer it";
    }
}
