package com.unprompted.tildefriends;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.os.Parcel;
import android.os.ParcelFileDescriptor;
import android.util.Log;

public class TildeFriendsSandboxService extends Service {
	public static final int START_CALL = IBinder.FIRST_CALL_TRANSACTION;

	Thread thread;

	public int onStartCommand(Intent intent, int flags, int start_id) {
		Log.w("tildefriends", "TildeFriendsSandboxService: onStartCommand");
		return super.onStartCommand(intent, flags, start_id);
	}

	public void onDestroy() {
		Log.w("tildefriends", "TildeFriendsSandboxService: onDestroy");
		super.onDestroy();
	}

	private void start_thread(int pipe_fd) {
		thread = new Thread(new Runnable() {
			@Override
			public void run() {
				Log.w("tildefriends", "Calling tf_sandbox_main.");
				int result = TildeFriendsActivity.tf_sandbox_main(pipe_fd);
				Log.w("tildefriends", "tf_sandbox_main returned " + result + ".");
			}
		});
		thread.start();
	}

	@Override
	public IBinder onBind(Intent intent) {
		return new Binder() {
			@Override
			protected boolean onTransact(int code, Parcel data, Parcel reply, int flags) {
				if (code == START_CALL) {
					ParcelFileDescriptor pfd = read_pfd(data);
					if (pfd != null) {
						Log.w("tildefriends", "fd is " + pfd.getFd());
						start_thread(pfd.detachFd());
						try {
							pfd.close();
						} catch (java.io.IOException e) {
						}
					}
					return true;
				}
				return false;
			}
		};
	}

	@SuppressWarnings("deprecation")
	static private ParcelFileDescriptor read_pfd(Parcel data) {
		return data.readParcelable(ParcelFileDescriptor.class.getClassLoader());
	}
}
