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;

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) {
		TildeFriendsActivity.log("TildeFriendsSandboxService: onStartCommand");
		return super.onStartCommand(intent, flags, start_id);
	}

	public void onDestroy() {
		TildeFriendsActivity.log("TildeFriendsSandboxService: onDestroy");
		super.onDestroy();
	}

	private void start_thread(int pipe_fd) {
		thread = new Thread(new Runnable() {
			@Override
			public void run() {
				TildeFriendsActivity.log("Calling tf_sandbox_main.");
				int result = TildeFriendsActivity.tf_sandbox_main(pipe_fd);
				TildeFriendsActivity.log("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) {
						TildeFriendsActivity.log("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());
	}
}
