package com.ikezo.callbackexample;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.telephony.TelephonyManager;
import android.view.Menu;
import android.view.View;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
	private String getPhoneNumber()
	{
		TelephonyManager telephony_manager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
	    return telephony_manager.getLine1Number();
	}
	
	public void requestCallback(View view)
	{
		String ip_address = "192.168.115.193";
		short http_api_port = 7780;
		String agent_phone_number = "2000";
		String company_name = "...";
		
		HttpClient httpclient = new DefaultHttpClient(); 
		HttpPost httppost = new HttpPost(String.format("http://%s:%s/", ip_address, http_api_port));
	
	    try
	    {
	        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
	        nameValuePairs.add(new BasicNameValuePair("Command", "Call"));
	        nameValuePairs.add(new BasicNameValuePair("CallerId", agent_phone_number));
	        nameValuePairs.add(new BasicNameValuePair("CallerDisplayName", company_name));
	        nameValuePairs.add(new BasicNameValuePair("Dialed", getPhoneNumber()));
	        nameValuePairs.add(new BasicNameValuePair("ResponseOzML",
	        		String.format("<Response><Delay>1</Delay><Speak>Welcome this is the %s company. Please wait for a moment until we can connect you to our assistant.</Speak><BlindTransfer>%s</BlindTransfer><Speak>Sorry, no agent is available, please try again later.</Speak></Response>",
	        				company_name, agent_phone_number)));
	
	        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
	
	        httpclient.execute(httppost);
	    }
	    catch (ClientProtocolException e)
	    {
	        System.err.println(e.getMessage());
	    }
	    catch (IOException e)
	    {
	    	System.err.println(e.getMessage());
	    }
	}
}
