package gr.mybook.myremoteservice;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.view.Menu;
import android.view.View;

public class MainActivity extends Activity {
    Messenger myService = null;
    boolean isConnected = false;

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

    private ServiceConnection myConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            myService = new Messenger(service);
            isConnected = true;
		  // Send a message to remote service
          SimpleDateFormat datetime = new SimpleDateFormat("HH:mm:ss dd/MM/yyyy", Locale.UK);
		  Message msg = Message.obtain();
		  Bundle b = new Bundle();
		  b.putString("key", datetime.format(new Date()));
		  msg.setData(b);
		  try {
                myService.send(msg);
		  } catch (RemoteException e) {
                   e.printStackTrace();
		    }
        }

        public void onServiceDisconnected(ComponentName className) {
		  myService = null;
            isConnected = false;
        }
     };

     public void onClick(View view){
     	Intent intent = new Intent("gr.mybook.myremoteservice");
     	bindService(intent, myConnection, Context.BIND_AUTO_CREATE);
     }
 
	@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;
	}

}
