/**
 * This file was auto-generated by the Titanium Module SDK helper for Android
 * Appcelerator Titanium Mobile
 * Copyright (c) 2009-2013 by Appcelerator, Inc. All Rights Reserved.
 * Licensed under the terms of the Apache Public License
 * Please see the LICENSE included with this distribution for details.
 *
 */
package in.shivakumars.crittercism;

import org.appcelerator.kroll.KrollDict;
import org.appcelerator.kroll.KrollModule;
import org.appcelerator.kroll.annotations.Kroll;

import org.appcelerator.titanium.TiApplication;
import org.appcelerator.kroll.common.Log;

import android.app.Activity;
import android.content.pm.PackageManager.NameNotFoundException;

import com.crittercism.app.Crittercism;
import com.crittercism.app.CrittercismConfig;

@Kroll.module(name = "Crittercism", id = "in.shivakumars.crittercism")
public class CrittercismModule extends KrollModule {

	// Standard Debugging variables
	private static final String TAG = "CrittercismModule";

	private Activity currentActivity;

	// You can define constants with @Kroll.constant, for example:
	// @Kroll.constant public static final String EXTERNAL_NAME = value;

	public CrittercismModule() {
		super();
	}

	@Kroll.onAppCreate
	public static void onAppCreate(TiApplication app) {
		Log.d(TAG, "inside onAppCreate");
		// put module init code that needs to run when the application is
		// created
	}

	// Methods
	@Kroll.method
	public void initializeCrittercism(KrollDict dict) {
		Log.d(TAG, "Crittercism Init called");
		currentActivity = TiApplication.getAppCurrentActivity();
		initCrittercism(dict);
	}

	private void initCrittercism(KrollDict dict) {

		

			String apiKey = (String) dict.get("apiKey");
			Log.d(TAG, apiKey);
			// Create the CrittercismConfig instance.
			CrittercismConfig config = new CrittercismConfig();
			
			Boolean includeVersionName = (Boolean)dict.get("includeVersionName");
			Boolean includeVersionCode = (Boolean)dict.get("includeVersionCode");
			
			
			if (includeVersionName!=null && includeVersionName) {
				// set the custom version name.
				try {
					config.setCustomVersionName(currentActivity
							.getPackageManager().getPackageInfo(
									currentActivity.getPackageName(), 0).versionName);
				} catch (NameNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			if (includeVersionCode!=null && includeVersionCode) {
				// Set the custom version name.
				config.setVersionCodeToBeIncludedInVersionString(true);
			}
			// Initialize.
			Crittercism.initialize(currentActivity.getApplicationContext(),
					apiKey, config);

			
				Crittercism.setUsername((String) dict.get("userName"));
			
		}
	

}
