package jp.co.corecorp.s3pdf;

import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

public class S3ServiceManager {
	private S3Context s3ctx;
	private List<S3Application> services;
	
	public S3ServiceManager(S3Context ctx) {
		s3ctx = ctx;
		services = new ArrayList<S3Application>(); 
	}
	
	public void connectService(String svn) throws S3Exception, S3TypeException {
		S3Application svc = new S3Application(s3ctx, svn);
		S3LocalStore ls = s3ctx.getLocalStore();
		S3Connection cn = s3ctx.getConnection();
		ls.registerService(svc);
		List<String> rsnList = ls.getResourceList(svc);
		int i;
		for( i = 0; i < rsnList.size(); i++) {
			String rsn = rsnList.get(i);
			S3Resource rsc = new S3Resource(svc, rsn);
			rsc.loadInfo();
			rsc.loadGadget();
			svc.addResource(rsc);
		}
		if( cn != null ) {
			cn.registerService(svc);
		}
		services.add(svc);
	}
	int getServiceCount() {
		return services.size();
	}
	S3Application getService(int index) {
		return services.get(index);
	}
	S3Application findService(String svn) {
		int i;
		for( i = 0; i < services.size(); i++ ) {
			S3Application svc = services.get(i);
			if( svc.getServiceName().equals(svn) ) {
				return svc; 
			}
		}
		return null;
	}
	
	public void sync(S3Application svc, Handler handler) throws S3SyncException {
		S3Application s = svc;
		Bundle startNotifyData = new Bundle();
		startNotifyData.putInt("C", S3Context.START_SYNCHRONIZE);
		Message startNotifyMsg = Message.obtain();
		startNotifyMsg.setData(startNotifyData);
		handler.sendMessage(startNotifyMsg);
		
		if( s != null ) {
			s.doSync(handler);
		} else {
			int i;
			int n = getServiceCount();
			for( i = 0; i < n; i++ ) {
				s = getService(i);
				s.doSync(handler);
			}
		}
		
		Bundle endNotifyData = new Bundle();
		endNotifyData.putInt("C", S3Context.END_SYNCHRONIZE_SYNC);
		Message endNotifyMsg = Message.obtain();
		endNotifyMsg.setData(endNotifyData);
		handler.sendMessage(endNotifyMsg);
	}
}
