/*
 * Copyright (c) 2012 Socialize Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package com.socialize;

import android.app.Activity;
import com.socialize.api.action.entity.EntityUtilsProxy;
import com.socialize.entity.Entity;
import com.socialize.listener.entity.EntityAddListener;
import com.socialize.listener.entity.EntityGetListener;
import com.socialize.listener.entity.EntityListListener;

import java.lang.reflect.Proxy;

/**
 * @author Jason Polites
 *
 */
public class EntityUtils {

	public static enum SortOrder {CREATION_DATE, TOTAL_ACTIVITY};

	static EntityUtilsProxy proxy;

	static {
		proxy = (EntityUtilsProxy) Proxy.newProxyInstance(
				EntityUtilsProxy.class.getClassLoader(),
				new Class[]{EntityUtilsProxy.class},
				new SocializeActionProxy("entityUtils"));	// Bean name
	}

	/**
	 * Saves or Creates an entity
	 * @param context The current context.
	 * @param e The entity to be created.
	 * @param listener A listener to handle the result.
	 */
	public static void saveEntity (Activity context, Entity e, EntityAddListener listener) {
		proxy.saveEntity(context, e, listener);
	}

	/**
	 * Retrieves an entity based on its key.
	 * @param context The current context.
	 * @param key The entity key.
	 * @param listener A listener to handle the result.
	 */
	public static void getEntity (Activity context, String key, EntityGetListener listener) {
		proxy.getEntity(context, key, listener);
	}

	/**
	 * Retrieves an entity based on its id.
	 * @param context The current context.
	 * @param id The entity id.
	 * @param listener A listener to handle the result.
	 */
	public static void getEntity (Activity context, long id, EntityGetListener listener) {
		proxy.getEntity(context, id, listener);
	}

	/**
	 * Retrieves all entities sorted by creation date.
	 * @param context The current context.
	 * @param start The start index for pagination (0 based).
	 * @param end The end index for pagination (0 based).
	 * @param listener A listener to handle the result.
	 */
	public static void getEntities (Activity context, int start, int end, EntityListListener listener) {
		proxy.getEntities(context, start, end, SortOrder.CREATION_DATE, listener);
	}

	/**
	 * Retrieves the entities designated by the given keys.
	 * @param context The current context.
	 * @param listener A listener to handle the result.
	 * @param keys One or more entity keys.
	 */
	public static void getEntities (Activity context, EntityListListener listener, String...keys) {
		proxy.getEntities(context, SortOrder.CREATION_DATE, listener, keys);
	}

	/**
	 * Retrieves all entities sorted by creation date.
	 * @param context The current context.
	 * @param start The start index for pagination (0 based).
	 * @param end The end index for pagination (0 based).
	 * @param sortOrder The sorting to be used (default is CREATION_DATE)
	 * @param listener A listener to handle the result.
	 */
	public static void getEntities (Activity context, int start, int end, SortOrder sortOrder, EntityListListener listener) {
		proxy.getEntities(context, start, end, sortOrder, listener);
	}

	/**
	 * Retrieves the entities designated by the given keys.
	 * @param context The current context.
	 * @param listener A listener to handle the result.
	 * @param sortOrder The sorting to be used (default is CREATION_DATE)
	 * @param keys One or more entity keys.
	 */
	public static void getEntities (Activity context, SortOrder sortOrder, EntityListListener listener, String...keys) {
		proxy.getEntities(context, sortOrder, listener, keys);
	}

	/**
	 * Uses the registered entity loader (if one exists) to load the entity denoted by the given entity key.
	 * @param context The current context.
	 * @param key The entity key.
	 * @param listener A listener to handle the result.
	 */
	public static void showEntity(Activity context, String key, EntityGetListener listener) {
		proxy.showEntity(context, key, listener);
	}

	/**
	 * Uses the registered entity loader (if one exists) to load the entity denoted by the given entity ID.
	 * @param context The current context.
	 * @param id The entity id.
	 * @param listener A listener to handle the result.
	 */
	public static void showEntity(Activity context, long id, EntityGetListener listener) {
		proxy.showEntity(context, id, listener);
	}
}


/*
 * Copyright (c) 2013 Socialize Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package com.socialize.ui;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.*;

/**
 * Default implementation of a SocializeActivityLifecycleListener
 * @author Jason Polites
 */
public class DefaultSocializeActivityLifecycleListener implements SocializeActivityLifecycleListener {

	/**
	 * Called BEFORE the default activity onCreate lifecycle event.
	 *
	 * @param activity           The calling activity.
	 * @param savedInstanceState Bundle contains the data it most recently supplied in onSaveInstanceState(Bundle). Note: Otherwise it is null.
	 */
	@Override
	public void onCreate(SocializeUIActivity activity, Bundle savedInstanceState) {

	}

	/**
	 * Called BEFORE the default activity onPause lifecycle event.
	 *
	 * @param activity The calling activity.
	 */
	@Override
	public void onPause(SocializeUIActivity activity) {

	}

	/**
	 * Called BEFORE the default activity onResume lifecycle event.
	 *
	 * @param activity The calling activity.
	 */
	@Override
	public void onResume(SocializeUIActivity activity) {

	}

	/**
	 * Called BEFORE the default activity onStart lifecycle event.
	 *
	 * @param activity The calling activity.
	 */
	@Override
	public void onStart(SocializeUIActivity activity) {

	}

	/**
	 * Called BEFORE the default activity onStop lifecycle event.
	 *
	 * @param activity The calling activity.
	 */
	@Override
	public void onStop(SocializeUIActivity activity) {

	}

	/**
	 * Called BEFORE the default activity onRestart lifecycle event.
	 *
	 * @param activity The calling activity.
	 */
	@Override
	public void onRestart(SocializeUIActivity activity) {

	}

	/**
	 * Called BEFORE the default activity onDestroy lifecycle event.
	 *
	 * @param activity The calling activity.
	 */
	@Override
	public void onDestroy(SocializeUIActivity activity) {

	}

	/**
	 * Called BEFORE the default activity onNewIntent lifecycle event.
	 *
	 * @param activity The calling activity.
	 * @param intent   The new intent that was started for the activity.
	 */
	@Override
	public void onNewIntent(SocializeUIActivity activity, Intent intent) {

	}

	/**
	 * Called BEFORE the default activity onBackPressed event.
	 *
	 * @param activity The calling activity.
	 * @return True to PREVENT the default implementation from executing.
	 */
	@Override
	public boolean onBackPressed(SocializeUIActivity activity) {
		return false;
	}

	/**
	 * Called BEFORE the default activity onTouchEvent event.
	 *
	 * @param activity The calling activity.
	 * @param event    The touch screen event being processed.
	 * @return True to PREVENT the default implementation from executing.
	 */
	@Override
	public boolean onTouchEvent(SocializeUIActivity activity, MotionEvent event) {
		return false;
	}

	/**
	 * Called BEFORE the default activity onActivityResult event.
	 *
	 * @param activity    The calling activity.
	 * @param requestCode The integer request code originally supplied to startActivityForResult(), allowing you to identify who this result came from.
	 * @param resultCode  The integer result code returned by the child activity through its setResult().
	 * @param data        An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
	 * @return True to PREVENT the default implementation from executing.
	 */
	@Override
	public boolean onActivityResult(SocializeUIActivity activity, int requestCode, int resultCode, Intent data) {
		return false;
	}

	/**
	 * Called BEFORE the default activity onCreateContextMenu event.
	 *
	 * @param activity The calling activity.
	 * @param menu     The context menu that is being built
	 * @param v        The view for which the context menu is being built
	 * @param menuInfo Extra information about the item for which the context menu should be shown. This information will vary depending on the class of v.
	 * @return True to PREVENT the default implementation from executing.
	 */
	@Override
	public boolean onCreateContextMenu(SocializeUIActivity activity, ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
		return false;
	}

	/**
	 * Called BEFORE the default activity onContextItemSelected event.
	 *
	 * @param activity The calling activity.
	 * @param item     The context menu item that was selected.
	 * @return True to PREVENT the default implementation from executing.
	 */
	@Override
	public boolean onContextItemSelected(SocializeUIActivity activity, MenuItem item) {
		return false;
	}

	/**
	 * Called BEFORE the default activity onContextMenuClosed event.
	 *
	 * @param activity The calling activity.
	 * @param menu     The context menu item that was selected.
	 * @return True to PREVENT the default implementation from executing.
	 */
	@Override
	public boolean onContextMenuClosed(SocializeUIActivity activity, Menu menu) {
		return false;
	}

	/**
	 * Called BEFORE the default activity onCreateOptionsMenu event.
	 *
	 * @param activity The calling activity.
	 * @param menu     The options menu in which you place your items.
	 * @return True to PREVENT the default implementation from executing.
	 */
	@Override
	public boolean onCreateOptionsMenu(SocializeUIActivity activity, Menu menu) {
		return false;
	}

	/**
	 * Called BEFORE the default activity onOptionsItemSelected event.
	 *
	 * @param activity The calling activity.
	 * @param item     The options menu item that was selected.
	 * @return True to PREVENT the default implementation from executing.
	 */
	@Override
	public boolean onOptionsItemSelected(SocializeUIActivity activity, MenuItem item) {
		return false;
	}

	/**
	 * Called BEFORE the default activity onOptionsMenuClosed event.
	 *
	 * @param activity The calling activity.
	 * @param menu     The options menu in which you place your items.
	 * @return True to PREVENT the default implementation from executing.
	 */
	@Override
	public boolean onOptionsMenuClosed(SocializeUIActivity activity, Menu menu) {
		return false;
	}

	/**
	 * Called BEFORE the default activity onMenuItemSelected event.
	 *
	 * @param activity  The calling activity.
	 * @param featureId The panel that the menu is in.
	 * @param item      he options menu item that was selected.
	 * @return True to PREVENT the default implementation from executing.
	 */
	@Override
	public boolean onMenuItemSelected(SocializeUIActivity activity, int featureId, MenuItem item) {
		return false;
	}

	/**
	 * Called BEFORE the default activity onMenuOpened event.
	 *
	 * @param activity  The calling activity.
	 * @param featureId The panel that the menu is in.
	 * @param menu      The options menu in which you place your items.
	 * @return True to PREVENT the default implementation from executing.
	 */
	@Override
	public boolean onMenuOpened(SocializeUIActivity activity, int featureId, Menu menu) {
		return false;
	}

	/**
	 * Called BEFORE the default activity onCreateDialog event.
	 *
	 * @param activity The calling activity.
	 * @param id       The id of the dialog.
	 * @param args     The dialog arguments provided to showDialog(int, Bundle).
	 * @return Returning null will cause the default implementation to execute.
	 */
	@Override
	public Dialog onCreateDialog(SocializeUIActivity activity, int id, Bundle args) {
		return null;
	}
}


/*
 * Copyright (c) 2012 Socialize Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package com.socialize.ui.dialog;

import android.app.Dialog;
import android.content.Context;
import android.view.Window;
import com.socialize.error.SocializeException;
import com.socialize.log.SocializeLogger;
import com.socialize.util.Drawables;

/**
 * @author Jason Polites
 *
 */
public abstract class BaseDialogFactory {

	protected Drawables drawables;
	protected SocializeLogger logger;

	// So we can mock
	protected Dialog newDialog(Context context) {
		Dialog dialog = new Dialog(context, android.R.style.Theme_Dialog);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

		// Register to prevent window leakage
		DialogRegistration.register(context, dialog);

		return dialog;
	}

	protected void handleError(String msg, SocializeException error) {
		if(logger != null) {
			logger.error(msg, error);
		}
		else {
			SocializeLogger.e(error.getMessage(), error);
		}
	}

	public void setLogger(SocializeLogger logger) {
		this.logger = logger;
	}

	public void setDrawables(Drawables drawables) {
		this.drawables = drawables;
	}
}


/*
 * Copyright (c) 2012 Socialize Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package com.socialize;

import android.app.Activity;
import com.socialize.api.action.comment.SubscriptionUtilsProxy;
import com.socialize.entity.Entity;
import com.socialize.listener.subscription.SubscriptionCheckListener;
import com.socialize.listener.subscription.SubscriptionResultListener;
import com.socialize.notifications.SubscriptionType;

import java.lang.reflect.Proxy;

/**
 * @author Jason Polites
 *
 */
public class SubscriptionUtils {
	static SubscriptionUtilsProxy subscriptionUtils;
	static {
		subscriptionUtils = (SubscriptionUtilsProxy) Proxy.newProxyInstance(
				SubscriptionUtilsProxy.class.getClassLoader(),
				new Class[]{SubscriptionUtilsProxy.class},
				new SocializeActionProxy("subscriptionUtils"));	// Bean name
	}

	/**
	 * Subscribes the current user to notifications for new comments on this entity.
	 * @param context The current context.
	 * @param e The entity.
	 * @param type The subscription type.
	 * @param listener A listener to handle the result.
	 */
	public static void subscribe (Activity context, Entity e, SubscriptionType type, SubscriptionResultListener listener) {
		subscriptionUtils.subscribe(context, e, type, listener);
	}

	/**
	 * Un-Subscribes the current user from notifications for new comments on this entity.
	 * @param context The current context.
	 * @param e The entity.
	 * @param type The subscription type.
	 * @param listener A listener to handle the result.
	 */
	public static void unsubscribe (Activity context, Entity e, SubscriptionType type, SubscriptionResultListener listener) {
		subscriptionUtils.unsubscribe(context, e, type, listener);
	}

	/**
	 * Determines if the current user is subscribed to notifications on new comments for the given entity.
	 * @param context The current context.
	 * @param e The entity.
	 * @param type The subscription type.
	 * @param listener A listener to handle the result.
	 */
	public static void isSubscribed (Activity context, Entity e, SubscriptionType type, SubscriptionCheckListener listener) {
		subscriptionUtils.isSubscribed(context, e, type, listener);
	}

}


/*
 * Copyright (c) 2012 Socialize Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package com.socialize.notifications;

import android.content.Context;
import android.os.Bundle;
import com.socialize.Socialize;
import com.socialize.error.SocializeException;

/**
 * @author Jason Polites
 *
 */
public class DirectEntityMessageTranslator implements MessageTranslator<SimpleNotificationMessage> {
	/*
	 * (non-Javadoc)
	 * @see com.socialize.notifications.MessageTranslator#translateTo(android.content.Context, android.os.Bundle, com.socialize.notifications.NotificationMessage)
	 */
	@Override
	public SimpleNotificationMessage translate(Context context, Bundle data, NotificationMessage message) throws SocializeException {
		SimpleNotificationMessage notify = new SimpleNotificationMessage();

		if(message.getEntityId() != null) {
			notify.setTitle(message.getText());
			notify.setText(message.getText());

			data.putLong( Socialize.ENTITY_ID , message.getEntityId());
		}
		else {
			throw new SocializeException("No entity id found in notification of type [" +
					message.getNotificationType() +
					"]");
		}
		return notify;
	}
}


/*
 * Copyright (c) 2012 Socialize Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package com.socialize.demo.implementations.facebook;

import android.content.Intent;
import com.facebook.*;
import com.facebook.model.GraphUser;
import com.socialize.demo.SDKDemoActivity;

import java.util.Arrays;

/**
 * @author Jason Polites
 *
 */
public class V3LoginActivity extends SDKDemoActivity {

	/* (non-Javadoc)
	 * @see com.socialize.demo.SDKDemoActivity#executeDemo(java.lang.String)
	 */
	@Override
	public void executeDemo(final String text) {
		// start Facebook Login
		Session.OpenRequest auth = new Session.OpenRequest(this);

		String[] permissions = {"publish_actions", "user_status"};

		auth.setPermissions(Arrays.asList(permissions));
		auth.setLoginBehavior(SessionLoginBehavior.SSO_WITH_FALLBACK);
		auth.setCallback(new Session.StatusCallback() {

			// callback when session changes state
			@Override
			public void call(Session session, SessionState state, Exception exception) {

				switch(state) {

					case OPENING:
						System.out.println("OPENING");
						break;

					case OPENED:
						System.out.println("OPENED");
						if (session.isOpened()) {
							// make request to the /me API
							Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
								// callback after Graph API response with user object
								@Override
								public void onCompleted(GraphUser user, Response response) {
									if(response.getError() != null) {
										handleError(V3LoginActivity.this, response.getError().getException());
									}
									else if (user != null) {
										handleResult("Success! " + user.getUsername());
									}
								}
							});
						}

						break;

					case CREATED:
						System.out.println("CREATED");
						break;

					case CREATED_TOKEN_LOADED:
						System.out.println("CREATED_TOKEN_LOADED");
						break;

					case OPENED_TOKEN_UPDATED:
						System.out.println("OPENED_TOKEN_UPDATED");
						break;

					case CLOSED:
						System.out.println("CLOSED");
						if(exception != null) {
							handleError(V3LoginActivity.this, exception);
						}
						else {
							handleCancel();
						}
						break;

					case CLOSED_LOGIN_FAILED:
						System.out.println("CLOSED_LOGIN_FAILED");
						if(exception != null) {
							handleError(V3LoginActivity.this, exception);
						}
						else {
							handleCancel();
						}
						break;

				}

			}
		});

		Session session = new Session.Builder(this).setApplicationId("268891373224435").build();
		Session.setActiveSession(session);
		session.openForPublish(auth);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Session activeSession = Session.getActiveSession();
		if(activeSession != null) {
			activeSession.onActivityResult(this, requestCode, resultCode, data);
		}
	}

	/* (non-Javadoc)
	 * @see com.socialize.demo.SDKDemoActivity#getButtonText()
	 */
	@Override
	public String getButtonText() {
		return "Login V3";
	}

	/* (non-Javadoc)
	 * @see com.socialize.demo.SDKDemoActivity#isTextEntryRequired()
	 */
	@Override
	public boolean isTextEntryRequired() {
		return false;
	}

}


/*
 * Copyright (c) 2012 Socialize Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package com.socialize.demo.implementations.share;

import com.socialize.ShareUtils;
import com.socialize.demo.SDKDemoActivity;
import com.socialize.entity.ListResult;
import com.socialize.entity.Share;
import com.socialize.error.SocializeException;
import com.socialize.listener.share.ShareListListener;

/**
 * @author Jason Polites
 *
 */
public class GetSharesByEntityActivity extends SDKDemoActivity {

	/* (non-Javadoc)
	 * @see com.socialize.demo.DemoActivity#executeDemo()
	 */
	@Override
	public void executeDemo(String text) {

		ShareUtils.getSharesByEntity(this, entity.getKey(), 0, PAGE_SIZE, new ShareListListener() {

			@Override
			public void onList(ListResult<Share> shares) {
				handleSocializeResult(shares);
			}

			@Override
			public void onError(SocializeException error) {
				handleError(GetSharesByEntityActivity.this, error);
			}
		});
	}

	@Override
	public boolean isTextEntryRequired() {
		return false;
	}

	/* (non-Javadoc)
	 * @see com.socialize.demo.DemoActivity#getButtonText()
	 */
	@Override
	public String getButtonText() {
		return "List " + PAGE_SIZE + " Shares for Current Entity";
	}
}


/*
 * Copyright (c) 2012 Socialize Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package com.socialize.launcher;

import android.app.Activity;
import android.os.Bundle;
import com.socialize.concurrent.ManagedAsyncTask;

/**
 * @author Jason Polites
 *
 */
public class AsyncLauncher extends ManagedAsyncTask<Void, Void, Boolean> {

	private Bundle extras;
	private LaunchListener listener;
	private Activity context;
	private Launcher launcher;

	private Exception error;

	public AsyncLauncher(Activity context, Launcher launcher, Bundle extras, LaunchListener listener) {
		super();
		this.launcher = launcher;
		this.extras = extras;
		this.listener = listener;
		this.context = context;
	}

	/* (non-Javadoc)
	 * @see android.os.AsyncTask#doInBackground(Params[])
	 */
	@Override
	protected Boolean doInBackground(Void... params) {
		try {
			return launcher.launch(context, extras);
		}
		catch (Exception e) {
			error = e;
		}

		return false;
	}

	@Override
	protected void onPostExecuteManaged(Boolean result) {
		if(listener != null) {
			if(error != null) {
				listener.onError(error);
			}
			else {
				listener.onAfterLaunch(result);
			}
		}
	}
}


/*
 * Copyright (c) 2012 Socialize Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package com.socialize.init;

import android.content.Context;
import com.socialize.SocializeService;
import com.socialize.api.SocializeSession;
import com.socialize.error.SocializeException;
import com.socialize.listener.SocializeListener;
import com.socialize.log.SocializeLogger;

/**
 * @author Jason Polites
 *
 */
public class DefaultInitializationAsserter implements SocializeInitializationAsserter {

	private SocializeLogger logger;

	/* (non-Javadoc)
	 * @see com.socialize.init.SocializeInitializationAsserter#assertAuthenticated(com.socialize.api.SocializeSession, com.socialize.listener.SocializeListener)
	 */
	@Override
	public boolean assertAuthenticated(SocializeService service, SocializeSession session, SocializeListener listener) {
		if(session != null) {
			return true;
		}
		else {
			if(listener != null) {
				if(logger != null) {
					listener.onError(new SocializeException(logger.getMessage(SocializeLogger.NOT_AUTHENTICATED)));
				}
				else {
					listener.onError(new SocializeException("Not authenticated"));
				}
			}
			if(logger != null) logger.error(SocializeLogger.NOT_AUTHENTICATED);
		}
		return false;
	}

	@Override
	public boolean assertInitialized(Context context, SocializeService service, SocializeListener listener) {
		boolean initialized = service.isInitialized(context);
		if(!initialized) {
			if(listener != null) {
				if(logger != null) {
					listener.onError(new SocializeException(logger.getMessage(SocializeLogger.NOT_INITIALIZED)));
				}
				else {
					listener.onError(new SocializeException("Not initialized"));
				}
			}
			if(logger != null) logger.error(SocializeLogger.NOT_INITIALIZED);
		}
		return initialized;
	}

	public void setLogger(SocializeLogger logger) {
		this.logger = logger;
	}
}


/*
 * Copyright (c) 2012 Socialize Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package com.socialize.demo.implementations.facebook;

import android.app.Activity;
import com.socialize.api.SocializeSession;
import com.socialize.demo.SDKDemoActivity;
import com.socialize.error.SocializeException;
import com.socialize.listener.SocializeAuthListener;
import com.socialize.networks.SocialNetwork;
import com.socialize.networks.SocialNetworkPostListener;
import com.socialize.networks.facebook.FacebookUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * @author Jason Polites
 *
 */
public class ListFriendsActivity extends SDKDemoActivity {

	/* (non-Javadoc)
	 * @see com.socialize.demo.DemoActivity#executeDemo()
	 */
	@Override
	public void executeDemo(String text) {

		// We need additional permissions for this
		String[] permissions = {"user_friends"};

		FacebookUtils.linkForRead(this, new SocializeAuthListener() {

			@Override
			public void onError(SocializeException error) {
				handleError(ListFriendsActivity.this, error);
			}

			@Override
			public void onCancel() {
				handleCancel();
			}

			@Override
			public void onAuthSuccess(SocializeSession session) {

				FacebookUtils.get(ListFriendsActivity.this, "me/friends", null, new SocialNetworkPostListener() {

					@Override
					public void onNetworkError(Activity context, SocialNetwork network, Exception error) {
						handleError(context, error);
					}

					@Override
					public void onCancel() {
						handleCancel();
					}

					@Override
					public void onAfterPost(Activity parent, SocialNetwork socialNetwork, JSONObject responseObject) {

						try {
							JSONArray jsonArray = responseObject.getJSONArray("data");

							StringBuilder builder = new StringBuilder();

							int len = jsonArray.length();

							for (int i = 0; i < len; i++) {
								JSONObject jsonObject = jsonArray.getJSONObject(i);
								if(jsonObject.has("name")) {
									if(i > 0) {
										builder.append("\n");
									}
									builder.append(jsonObject.get("name"));
								}
							}

							handleResult(builder.toString());
						}
						catch (JSONException e) {
							handleError(parent, e);
						}
					}
				});
			}

			@Override
			public void onAuthFail(SocializeException error) {
				handleError(ListFriendsActivity.this, error);
			}
		}, permissions);
	}

	@Override
	public boolean isTextEntryRequired() {
		return false;
	}

	/* (non-Javadoc)
	 * @see com.socialize.demo.DemoActivity#getButtonText()
	 */
	@Override
	public String getButtonText() {
		return "List My Friends";
	}
}


/*
 * Copyright (c) 2012 Socialize Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package com.socialize.api.action.entity;

import com.socialize.EntityUtils.SortOrder;
import com.socialize.api.SocializeApi;
import com.socialize.api.SocializeSession;
import com.socialize.config.SocializeConfig;
import com.socialize.entity.Entity;
import com.socialize.entity.ListResult;
import com.socialize.error.SocializeApiError;
import com.socialize.error.SocializeException;
import com.socialize.listener.entity.EntityListListener;
import com.socialize.listener.entity.EntityListener;
import com.socialize.provider.SocializeProvider;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Jason Polites
 *
 */
public class SocializeEntitySystem extends SocializeApi<Entity, SocializeProvider<Entity>> implements EntitySystem {

	public SocializeEntitySystem(SocializeProvider<Entity> provider) {
		super(provider);
	}

	@Override
	public Entity getEntitySynchronous(SocializeSession session, long id) throws SocializeException {
		ListResult<Entity> list = list(session, ENDPOINT, null, 0, 1, String.valueOf(id));
		if(list != null) {
			List<Entity> items = list.getItems();
			if(items != null && items.size() > 0) {
				return items.get(0);
			}
		}
		return null;
	}

	/*
	 * (non-Javadoc)
	 * @see com.socialize.api.action.EntitySystem#addEntity(com.socialize.api.SocializeSession, com.socialize.entity.Entity, com.socialize.listener.entity.EntityListener)
	 */
	@Override
	public void addEntity(SocializeSession session, Entity entity, EntityListener listener) {
		List<Entity> list = new ArrayList<Entity>(1);
		list.add(entity);
		postAsync(session, ENDPOINT, list, listener);
	}

	protected EntityListListener getListenerForGet(final EntityListener listener, final String notFoundMessage) {
		return new EntityListListener() {

			@Override
			public void onError(SocializeException error) {
				listener.onError(error);
			}

			@Override
			public void onList(ListResult<Entity> entities) {
				boolean is404 = false;
				if(entities != null) {
					List<Entity> items = entities.getItems();
					if(items != null && items.size() > 0) {
						listener.onGet(items.get(0));
					}
					else {
						is404 = true;
					}
				}
				else {
					is404 = true;
				}

				if(is404) {
					onError(new SocializeApiError(404, notFoundMessage));
				}
			}
		};
	}

	@Override
	public void getEntity(SocializeSession session, long id, EntityListener listener) {
		listAsync(session, ENDPOINT, null, 0, 1, getListenerForGet(listener, "No entity found with id [" + id + "]"), String.valueOf(id));
	}

	/* (non-Javadoc)
	 * @see com.socialize.api.action.EnitySystem#getEntity(com.socialize.api.SocializeSession, java.lang.String, com.socialize.listener.entity.EntityListener)
	 */
	@Override
	public void getEntity(SocializeSession session, final String key, final EntityListener listener) {
		listAsync(session, ENDPOINT, key, null, null, 0, 1, getListenerForGet(listener, "No entity found with key [" + key + "]"));
	}

	/* (non-Javadoc)
	 * @see com.socialize.api.action.EnitySystem#listEntities(com.socialize.api.SocializeSession, com.socialize.listener.entity.EntityListener, java.lang.String)
	 */
	@Override
	public void getEntities(SocializeSession session, SortOrder sortOrder, EntityListener listener, String...keys) {
		Map<String, String> extraParams = null;

		if(!sortOrder.equals(SortOrder.CREATION_DATE)) {
			extraParams = new HashMap<String, String>();
			extraParams.put("sort", sortOrder.name().toLowerCase() );
		}

		listAsync(session, ENDPOINT, null, "entity_key", extraParams, 0, SocializeConfig.MAX_LIST_RESULTS, listener, keys);
	}

	/*
	 * (non-Javadoc)
	 * @see com.socialize.api.action.entity.EntitySystem#getEntities(com.socialize.api.SocializeSession, int, int, com.socialize.listener.entity.EntityListener)
	 */
	@Override
	public void getEntities(SocializeSession session, int start, int end, SortOrder sortOrder, EntityListener listener) {
		Map<String, String> extraParams = null;

		if(!sortOrder.equals(SortOrder.CREATION_DATE)) {
			extraParams = new HashMap<String, String>();
			extraParams.put("sort", sortOrder.name().toLowerCase() );
		}

		listAsync(session, ENDPOINT, null, "entity_key", extraParams, start, end, listener);
	}
}


/*
 * Copyright (c) 2012 Socialize Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package com.socialize.notifications;

import android.content.Context;
import com.socialize.Socialize;
import com.socialize.api.SocializeSession;
import com.socialize.config.SocializeConfig;
import com.socialize.error.SocializeException;
import com.socialize.listener.SocializeAuthListener;
import com.socialize.log.SocializeLogger;
import com.socialize.util.AppUtils;
import com.socialize.util.StringUtils;

/**
 * Checks for notification registrations.
 * @author Jason Polites
 *
 */
public class NotificationChecker {

	private NotificationRegistrationSystem notificationRegistrationSystem;
	private NotificationRegistrationState notificationRegistrationState;
	private SocializeLogger logger;
	private SocializeConfig config;
	private AppUtils appUtils;
	private boolean checked = false;
	private boolean checking = false;

	public void checkRegistrations(final Context context) {
		if(!checked) {
			Socialize.getSocialize().authenticate(context, new SocializeAuthListener() {
				@Override
				public void onError(SocializeException error) {
					logError(error);
				}

				@Override
				public void onCancel() {
					// Ignore
				}

				@Override
				public void onAuthSuccess(final SocializeSession session) {
					new Thread() {
						@Override
						public void run() {
							checked = checkRegistrations(context, session);
						}
					}.start();
				}

				@Override
				public void onAuthFail(SocializeException error) {
					logError(error);
				}
			});
		}
	}

	protected void logError(Exception e) {
		if(logger != null) {
			logger.error("Error checking notification state", e);
		}
		else {
			SocializeLogger.e(e.getMessage(), e);
		}
	}

	/**
	 * Called at application startup.
	 * @param context
	 */
	public boolean checkRegistrations(Context context, SocializeSession session) {

		boolean checked = false;

		if(!checking) {
			checking = true;

			try {

				if(appUtils.isNotificationsAvailable(context)) {

					if(config.getBooleanProperty(SocializeConfig.SOCIALIZE_CHECK_NOTIFICATIONS, true)) {
						if(logger != null && logger.isDebugEnabled()) {
							logger.debug("Checking GCM registration state");
						}

						boolean c2DMRegistered = notificationRegistrationSystem.isRegisteredC2DM(context);
						boolean socRegistered = notificationRegistrationSystem.isRegisteredSocialize(context, session.getUser());

						if(!c2DMRegistered || !socRegistered) {

							// Reload
							notificationRegistrationState.reload(context);

							c2DMRegistered = notificationRegistrationSystem.isRegisteredC2DM(context);
							socRegistered = notificationRegistrationSystem.isRegisteredSocialize(context, session.getUser());

							if(!c2DMRegistered || !socRegistered) {
								if(!c2DMRegistered && config.getBooleanProperty(SocializeConfig.GCM_REGISTRATION_ENABLED, true)) {

									if(notificationRegistrationSystem.isRegistrationPending()) {
										if(logger != null && logger.isDebugEnabled()) {
											logger.debug("GCM Registration already pending");
										}
									}
									else {
										if(logger != null && logger.isInfoEnabled()) {
											logger.info("Not registered with GCM, sending registration request...");
										}

										notificationRegistrationSystem.registerC2DMAsync(context);
									}
								}
								else if(!socRegistered && !StringUtils.isEmpty(notificationRegistrationState.getC2DMRegistrationId())) {

									if(notificationRegistrationSystem.isSocializeRegistrationPending()) {
										if(logger != null && logger.isDebugEnabled()) {
											logger.debug("Registration already pending with Socialize for GCM");
										}
									}
									else {
										if(logger != null && logger.isInfoEnabled()) {
											logger.info("Not registered with Socialize for GCM, registering...");
										}

										notificationRegistrationSystem.registerSocialize(context, notificationRegistrationState.getC2DMRegistrationId());
									}
								}
							}
							else {
								if(logger != null && logger.isDebugEnabled()) {
									logger.debug("GCM registration OK");
								}
							}
						}
						else {
							if(logger != null && logger.isDebugEnabled()) {
								logger.debug("GCM registration OK");
							}
						}

						checked = true;
					}
					else {
						if(logger != null && logger.isWarnEnabled()) {
							logger.warn("GCM registration check skipped");
						}
					}
				}
				else {
					if(logger != null && logger.isInfoEnabled()) {
						logger.info("Notifications not enabled.  Check the AndroidManifest.xml for correct configuration.");
					}

					checked = true;
				}
			}
			finally {
				checking = false;
			}
		}

		return checked;
	}

	public void setNotificationRegistrationSystem(NotificationRegistrationSystem notificationRegistrationSystem) {
		this.notificationRegistrationSystem = notificationRegistrationSystem;
	}

	public void setNotificationRegistrationState(NotificationRegistrationState notificationRegistrationState) {
		this.notificationRegistrationState = notificationRegistrationState;
	}

	public void setLogger(SocializeLogger logger) {
		this.logger = logger;
	}

	public void setConfig(SocializeConfig config) {
		this.config = config;
	}

	public void setAppUtils(AppUtils appUtils) {
		this.appUtils = appUtils;
	}
}


/*
 * Copyright (c) 2012 Socialize Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package com.socialize.notifications;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.socialize.Socialize;
import com.socialize.SocializeService;

/**
 * @author Jason Polites
 *
 */
public class SocializeBroadcastReceiver extends BroadcastReceiver {

	/* (non-Javadoc)
	 * @see android.content.BroadcastReceiver#onReceive(android.content.Context, android.content.Intent)
	 */
	@Override
	public void onReceive(Context context, Intent intent) {
		getSocialize().handleBroadcastIntent(context, intent);
	}

	// So we can mock
	protected SocializeService getSocialize() {
		return Socialize.getSocialize();
	}
}


/*
 * Copyright (c) 2012 Socialize Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package com.socialize.ui.profile.activity;

import android.app.Activity;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.Typeface;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.TextAppearanceSpan;
import android.util.TypedValue;
import android.view.View;
import android.widget.TextView;
import com.socialize.Socialize;
import com.socialize.api.action.ActionType;
import com.socialize.entity.SocializeAction;
import com.socialize.entity.User;
import com.socialize.log.SocializeLogger;
import com.socialize.ui.SocializeEntityLoader;
import com.socialize.ui.util.Colors;
import com.socialize.util.DisplayUtils;
import com.socialize.util.StringUtils;

/**
 * @author Jason Polites
 *
 */
public class UserActivityActionText extends TextView implements UserActivityAction {

	private Colors colors;
	private int contentFontSize = 12;
	private int titleFontSize = 11;
	private DisplayUtils displayUtils;
	private SocializeLogger logger;

	public UserActivityActionText(Context context) {
		super(context);
	}

	/* (non-Javadoc)
	 * @see com.socialize.ui.profile.activity.UserActivityAction#init()
	 */
	@Override
	public void init() {
		setBackgroundColor(0x00000000);
	}

	/* (non-Javadoc)
	 * @see com.socialize.ui.profile.activity.UserActivityAction#setAction(com.socialize.entity.SocializeAction)
	 */
	@Override
	public void setAction(Context context, final SocializeAction action) {
		try {
			doSetAction(action);
		}
		catch (Exception e) {
			setText("Error!");

			if(logger != null) {
				logger.error("Error rendering action text", e);
			}
			else {
				SocializeLogger.e(e.getMessage(), e);
			}
		}
	}

	protected void doSetAction(final SocializeAction action) {

		int contentFontSizeDip = displayUtils.getDIP(contentFontSize);

		StringBuilder builder = new StringBuilder();

		boolean canLoad = false;

		final SocializeEntityLoader entityLoader = Socialize.getSocialize().getEntityLoader();
		if(entityLoader != null) {

			canLoad = entityLoader.canLoad(getContext(), action.getEntity());

			if(canLoad) {
				setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						entityLoader.loadEntity((Activity)getContext(), action.getEntity());
					}
				});
			}
		}

		setTextSize(TypedValue.COMPLEX_UNIT_DIP, titleFontSize);

		String name = "";

		User user = action.getUser();

		if(user != null) {
			name = user.getFirstName();

			if(StringUtils.isEmpty(name)) {
				name = user.getDisplayName();
			}
			if(name == null) {
				name = "";
			}
		}

		builder.append(name);

		String actionText = null;

		// Do the intro text
		switch(action.getActionType()) {
			case COMMENT:
				builder.append(" commented on ");
				actionText = StringUtils.replaceNewLines(action.getDisplayText(), 3, 2);
				break;
			case LIKE:
				builder.append(" liked ");
				break;
			case SHARE:
				actionText = action.getDisplayText();
				builder.append(" shared ");
				break;
		}

		String textSoFar = builder.toString();

		String entityName = StringUtils.ellipsis(action.getEntityDisplayName(), 30);

		if(!StringUtils.isEmpty(entityName)) {
			entityName = StringUtils.encodeUtf8(entityName);
		}
		else {
			entityName = "";
		}

		int entityNameStartIndex = textSoFar.length();
		int entityNameEndIndex = entityNameStartIndex + entityName.length();
		int actionTextStartIndex = 0;
		int actionTextEndIndex = 0;

		builder.append(entityName);

		if(actionText != null) {

			actionText = StringUtils.encodeUtf8(actionText);

			builder.append("\n\n");

			actionTextStartIndex = entityNameEndIndex + 2; // Plus 2 for the new lines and the end of the entity name.

			if(action.getActionType().equals(ActionType.COMMENT)) {
				builder.append("\"");
				builder.append(actionText);
				builder.append("\"");

				actionTextEndIndex = actionTextStartIndex + actionText.length() + 2;  // Plus 2 for the quotes;
			}
			else {
				builder.append(actionText);
				actionTextEndIndex = actionTextStartIndex + actionText.length();
			}
		}

		Spannable spannable = new SpannableString(builder.toString());

		if(canLoad) {

			ColorStateList linkColor = new ColorStateList(
		            new int[][] {
		                new int[] { android.R.attr.state_pressed },
		                new int[0],
		            }, new int[] {
		                Color.DKGRAY,
		                colors.getColor(Colors.SOCIALIZE_BLUE)
		            });

			TextAppearanceSpan textAppearanceSpan = new TextAppearanceSpan("sans", Typeface.BOLD, contentFontSizeDip, linkColor, linkColor);
			spannable.setSpan(textAppearanceSpan, entityNameStartIndex, entityNameEndIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		}

		if(actionText != null) {

			ColorStateList bodyColor = new ColorStateList(
		            new int[][] {
			                new int[] { android.R.attr.state_pressed },
			                new int[0],
			            }, new int[] {
			                Color.DKGRAY,
			                colors.getColor(Colors.BODY)
			            });

			TextAppearanceSpan textAppearanceSpan = new TextAppearanceSpan("serif", Typeface.ITALIC, contentFontSizeDip, bodyColor, bodyColor);
			spannable.setSpan(textAppearanceSpan, actionTextStartIndex, actionTextEndIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		}

		setText(spannable);
	}

	/* (non-Javadoc)
	 * @see com.socialize.ui.profile.activity.UserActivityAction#setContentFontSize(int)
	 */
	@Override
	public void setContentFontSize(int contentFontSize) {
		this.contentFontSize = contentFontSize;
	}

	/* (non-Javadoc)
	 * @see com.socialize.ui.profile.activity.UserActivityAction#setTitleFontSize(int)
	 */
	@Override
	public void setTitleFontSize(int titleFontSize) {
		this.titleFontSize = titleFontSize;
	}

	public void setColors(Colors colors) {
		this.colors = colors;
	}

	public void setDisplayUtils(DisplayUtils deviceUtils) {
		this.displayUtils = deviceUtils;
	}

	public void setLogger(SocializeLogger logger) {
		this.logger = logger;
	}
}


/*
 * Copyright (c) 2012 Socialize Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package com.socialize.demo.implementations.twitter;

import com.socialize.api.SocializeSession;
import com.socialize.auth.AuthProviderType;
import com.socialize.auth.UserProviderCredentials;
import com.socialize.demo.SDKDemoActivity;
import com.socialize.error.SocializeException;
import com.socialize.listener.SocializeAuthListener;
import com.socialize.networks.twitter.TwitterUtils;

/**
 * @author Jason Polites
 *
 */
public class GetTokenActivity extends SDKDemoActivity {

	/* (non-Javadoc)
	 * @see com.socialize.demo.DemoActivity#executeDemo()
	 */
	@Override
	public void executeDemo(String text) {

		TwitterUtils.link(this, new SocializeAuthListener() {

			@Override
			public void onError(SocializeException error) {
				handleError(GetTokenActivity.this, error);
			}

			@Override
			public void onCancel() {
				handleCancel();
			}

			@Override
			public void onAuthSuccess(SocializeSession session) {
				UserProviderCredentials userProviderCredentials = session.getUserProviderCredentials(AuthProviderType.TWITTER);
				handleResult(userProviderCredentials.getAccessToken());
			}

			@Override
			public void onAuthFail(SocializeException error) {
				handleError(GetTokenActivity.this, error);
			}
		});
	}

	@Override
	public boolean isTextEntryRequired() {
		return false;
	}

	/* (non-Javadoc)
	 * @see com.socialize.demo.DemoActivity#getButtonText()
	 */
	@Override
	public String getButtonText() {
		return "Get Access Token";
	}
}


/*
 * Copyright (C) 2010 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.socialize.google.gson.stream;

import com.socialize.google.gson.internal.JsonReaderInternalAccess;
import com.socialize.google.gson.internal.bind.JsonTreeReader;

import java.io.Closeable;
import java.io.EOFException;
import java.io.IOException;
import java.io.Reader;

/**
 * Reads a JSON (RFC 4627)
 * encoded value as a stream of tokens. This stream includes both literal
 * values (strings, numbers, booleans, and nulls) as well as the begin and
 * end delimiters of objects and arrays. The tokens are traversed in
 * depth-first order, the same order that they appear in the JSON document.
 * Within JSON objects, name/value pairs are represented by a single token.
 *
 *
Parsing JSON

 * To create a recursive descent parser for your own JSON streams, first create
 * an entry point method that creates a {@code JsonReader}.
 *
 *
Next, create handler methods for each structure in your JSON text. You'll
 * need a method for each object type and for each array type.
 *

 *
Within array handling methods, first call {@link
 *       #beginArray} to consume the array's opening bracket. Then create a
 *       while loop that accumulates values, terminating when {@link #hasNext}
 *       is false. Finally, read the array's closing bracket by calling {@link
 *       #endArray}.
 *
Within object handling methods, first call {@link
 *       #beginObject} to consume the object's opening brace. Then create a
 *       while loop that assigns values to local variables based on their name.
 *       This loop should terminate when {@link #hasNext} is false. Finally,
 *       read the object's closing brace by calling {@link #endObject}.
 *

 *
When a nested object or array is encountered, delegate to the
 * corresponding handler method.
 *
 *
When an unknown name is encountered, strict parsers should fail with an
 * exception. Lenient parsers should call {@link #skipValue()} to recursively
 * skip the value's nested tokens, which may otherwise conflict.
 *
 *
If a value may be null, you should first check using {@link #peek()}.
 * Null literals can be consumed using either {@link #nextNull()} or {@link
 * #skipValue()}.
 *
 *
Example

 * Suppose we'd like to parse a stream of messages such as the following:
 {@code
 * [
 *   {
 *     "id": 912345678901,
 *     "text": "How do I read a JSON stream in Java?",
 *     "geo": null,
 *     "user": {
 *       "name": "json_newb",
 *       "followers_count": 41
 *      }
 *   },
 *   {
 *     "id": 912345678902,
 *     "text": "@json_newb just use JsonReader!",
 *     "geo": [50.454722, -104.606667],
 *     "user": {
 *       "name": "jesse",
 *       "followers_count": 2
 *     }
 *   }
 * ]}

 * This code implements the parser for the above structure:
   {@code
 *
 *   public List<Message> readJsonStream(InputStream in) throws IOException {
 *     JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
 *     try {
 *       return readMessagesArray(reader);
 *     } finally {
 *       reader.close();
 *     }
 *   }
 *
 *   public List<Message> readMessagesArray(JsonReader reader) throws IOException {
 *     List<Message> messages = new ArrayList<Message>();
 *
 *     reader.beginArray();
 *     while (reader.hasNext()) {
 *       messages.add(readMessage(reader));
 *     }
 *     reader.endArray();
 *     return messages;
 *   }
 *
 *   public Message readMessage(JsonReader reader) throws IOException {
 *     long id = -1;
 *     String text = null;
 *     User user = null;
 *     List<Double> geo = null;
 *
 *     reader.beginObject();
 *     while (reader.hasNext()) {
 *       String name = reader.nextName();
 *       if (name.equals("id")) {
 *         id = reader.nextLong();
 *       } else if (name.equals("text")) {
 *         text = reader.nextString();
 *       } else if (name.equals("geo") && reader.peek() != JsonToken.NULL) {
 *         geo = readDoublesArray(reader);
 *       } else if (name.equals("user")) {
 *         user = readUser(reader);
 *       } else {
 *         reader.skipValue();
 *       }
 *     }
 *     reader.endObject();
 *     return new Message(id, text, user, geo);
 *   }
 *
 *   public List<Double> readDoublesArray(JsonReader reader) throws IOException {
 *     List<Double> doubles = new ArrayList<Double>();
 *
 *     reader.beginArray();
 *     while (reader.hasNext()) {
 *       doubles.add(reader.nextDouble());
 *     }
 *     reader.endArray();
 *     return doubles;
 *   }
 *
 *   public User readUser(JsonReader reader) throws IOException {
 *     String username = null;
 *     int followersCount = -1;
 *
 *     reader.beginObject();
 *     while (reader.hasNext()) {
 *       String name = reader.nextName();
 *       if (name.equals("name")) {
 *         username = reader.nextString();
 *       } else if (name.equals("followers_count")) {
 *         followersCount = reader.nextInt();
 *       } else {
 *         reader.skipValue();
 *       }
 *     }
 *     reader.endObject();
 *     return new User(username, followersCount);
 *   }}

 *
 *
Number Handling

 * This reader permits numeric values to be read as strings and string values to
 * be read as numbers. For example, both elements of the JSON array {@code
 * [1, "1"]} may be read using either {@link #nextInt} or {@link #nextString}.
 * This behavior is intended to prevent lossy numeric conversions: double is
 * JavaScript's only numeric type and very large values like {@code
 * 9007199254740993} cannot be represented exactly on that platform. To minimize
 * precision loss, extremely large values should be written and read as strings
 * in JSON.
 *
 *
Non-Execute Prefix

 * Web servers that serve private data using JSON may be vulnerable to Cross-site
 * request forgery attacks. In such an attack, a malicious site gains access
 * to a private JSON file by executing it with an HTML {@code


/*
 * Copyright (c) 2012 Socialize Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package com.socialize;

import android.app.Activity;
import android.content.Context;
import com.socialize.api.action.share.ShareOptions;
import com.socialize.api.action.share.ShareUtilsProxy;
import com.socialize.api.action.share.SocialNetworkDialogListener;
import com.socialize.api.action.share.SocialNetworkShareListener;
import com.socialize.entity.Entity;
import com.socialize.entity.User;
import com.socialize.listener.share.ShareAddListener;
import com.socialize.listener.share.ShareGetListener;
import com.socialize.listener.share.ShareListListener;
import com.socialize.networks.SocialNetwork;
import com.socialize.ui.auth.AuthDialogListener;

import java.lang.reflect.Proxy;

/**
 * Used to perform all default sharing operations like Facebook, Twitter, Email and SMS sharing.
 * @author Jason Polites
 */
public class ShareUtils {

	/**
	 * Used to instruct the dialog to display the Email option.
	 */
	public static final int EMAIL = 1;

	/**
	 * Used to instruct the dialog to display the SMS option.
	 */
	public static final int SMS = 1<<1;

	/**
	 * Used to instruct the dialog to display the Facebook option.
	 */
	public static final int FACEBOOK = 1<<2;

	/**
	 * Used to instruct the dialog to display the Twitter option.
	 */
	public static final int TWITTER = 1<<3;

	/**
	 * Used to instruct the dialog to display the "remember these networks" checkbox.
	 */
	public static final int SHOW_REMEMBER = 1<<4;

	/**
	 * Used to instruct the dialog to display the "more options" link.
	 */
	public static final int MORE_OPTIONS = 1<<5;

	/**
	 * Used to instruct the dialog to display the Google Plus option.
	 */
	public static final int GOOGLE_PLUS = 1<<6;

	/**
	 * Used to indicate that the continue button should always be enabled.
	 */
	public static final int ALWAYS_CONTINUE = 1<<7;

	/**
	 * Displays only Social Network options.
	 */
	public static final int SOCIAL = FACEBOOK|TWITTER|GOOGLE_PLUS;

	/**
	 * The default display settings for the share dialog.
	 */
	public static final int DEFAULT = EMAIL|SMS|FACEBOOK|TWITTER|GOOGLE_PLUS|MORE_OPTIONS;

	public static final String EXTRA_TITLE = "title";
	public static final String EXTRA_TEXT = "text";
	public static final String EXTRA_SUBJECT = "subject";

	static ShareUtilsProxy proxy;

	static {
		proxy = (ShareUtilsProxy) Proxy.newProxyInstance(
				ShareUtilsProxy.class.getClassLoader(),
				new Class[]{ShareUtilsProxy.class},
				new SocializeActionProxy("shareUtils")); // Bean name
	}

	/**
	 * Returns the default sharing options for the user.
	 * @param context The current context.
	 * @return The default sharing options for the user.
	 */
	public static ShareOptions getUserShareOptions(Context context) {
		return proxy.getUserShareOptions(context);
	}

	/**
	 * Displays the link dialog to allow the user to link to their Twitter or Facebook account.
	 * @param context The current context.
	 * @param listener A listener to handle events from the link.
	 */
	public static void showLinkDialog (Activity context, AuthDialogListener listener) {
		proxy.showLinkDialog(context, listener);
	}

	/**
	 * Pre-loads the share dialog in the background to improve load speed and end user responsiveness.
	 * @param context The current context.
	 */
	public static void preloadShareDialog (Activity context) {
		proxy.preloadShareDialog(context);
	}

	/**
	 * Pre-loads the link dialog in the background to improve load speed and end user responsiveness.
	 * @param context The current context.
	 */
	public static void preloadLinkDialog (Activity context) {
		proxy.preloadLinkDialog(context);
	}

	/**
	 * Displays the default share dialog.  In most cases this is the simplest version to use.
	 * @param context The current context.
	 * @param entity The entity being shared.
	 */
	public static void showShareDialog (Activity context, Entity entity) {
		proxy.showShareDialog(context, entity, DEFAULT, null, null);
	}

	/**
	 * Displays the default share dialog and allows for the handling of share dialog events.
	 * @param context The current context.
	 * @param entity The entity being shared.
	 * @param listener A listener to handle events on the dialog.
	 */
	public static void showShareDialog (Activity context, Entity entity, SocialNetworkDialogListener listener) {
		proxy.showShareDialog(context, entity, DEFAULT, listener, listener);
	}

	/**
	 * Displays the default share dialog and allows for the handling of share events.
	 * @param context The current context.
	 * @param entity The entity being shared.
	 * @param listener A listener to handle events.
	 * @param options Display options for the dialog.  These are bit flags taken from ShareUtils.
	 * @see ShareUtils#DEFAULT
	 * @see ShareUtils#SOCIAL
	 */
	public static void showShareDialog (Activity context, Entity entity, SocialNetworkDialogListener listener, int options) {
		proxy.showShareDialog(context, entity, options, listener, listener);
	}

	/**
	 * Shares the given entity via email.  This method with launch the default email application on the device.
	 * @param context The current context.
	 * @param entity The entity being shared.
	 * @param listener A listener to handle events.
	 */
	public static void shareViaEmail(Activity context, Entity entity, ShareAddListener listener) {
		proxy.shareViaEmail(context, entity, listener);
	}

	/**
	 * Shares the given entity via Google+.  This method with launch the Google+ application on the device.
	 * @param context The current context.
	 * @param entity The entity being shared.
	 * @param listener A listener to handle events.
	 */
	public static void shareViaGooglePlus(Activity context, Entity entity, ShareAddListener listener) {
		proxy.shareViaGooglePlus(context, entity, listener);
	}

	/**
	 * Shares the given entity via a user selected medium.  This method with launch the default application share dialog on the device.
	 * @param context The current context.
	 * @param entity The entity being shared.
	 * @param listener A listener to handle events.
	 */
	public static void shareViaOther(Activity context, Entity entity, ShareAddListener listener) {
		proxy.shareViaOther(context, entity, listener);
	}

	/**
	 * Shares the given entity via SMS.  This method with launch the default SMS application on the device.
	 * @param context The current context.
	 * @param entity The entity being shared.
	 * @param listener A listener to handle events.
	 */
	public static void shareViaSMS(Activity context, Entity entity, ShareAddListener listener) {
		proxy.shareViaSMS(context, entity, listener);
	}

	/**
	 * Shares the given entity via a Social Network such as Twitter or Facebook.  This will prompt the user to select a network.
	 * @param context The current context.
	 * @param entity The entity being shared.
	 * @param shareOptions Options for the share.  If text is available for the share it can be specified here.
	 * @param listener A listener to handle events.
	 */
	public static void shareViaSocialNetworks(Activity context, Entity entity, ShareOptions shareOptions, SocialNetworkShareListener listener, SocialNetwork...networks) {
		proxy.shareViaSocialNetworks(context, entity, shareOptions, listener, networks);
	}

	/**
	 * Retrieves a single share event based on ID.
	 * @param context The current context.
	 * @param listener A listener to handle the result.
	 * @param id The ID of the share.
	 */
	public static void getShare (Activity context, ShareGetListener listener, long id) {
		proxy.getShare(context, listener, id);
	}

	/**
	 * Retrieves multiple share events based on ID.
	 * @param context The current context.
	 * @param listener A listener to handle the result.
	 * @param ids One or more IDs for the shares returned.
	 */
	public static void getShares (Activity context, ShareListListener listener, long...ids) {
		proxy.getShares(context, listener, ids);
	}

	/**
	 * Retrieves all share events performed by the given user.
	 * @param context The current context.
	 * @param user The user who performed the share(s).
	 * @param start The start index for the result set (0 indexed).
	 * @param end The end index for the result set.
	 * @param listener A listener to handle the result.
	 */
	public static void getSharesByUser (Activity context, User user, int start, int end, ShareListListener listener) {
		proxy.getSharesByUser(context, user, start, end, listener);
	}

	/**
	 * Retrieves all share events performed on the given entity.
	 * @param context The current context.
	 * @param entityKey The key of the entity that was shared.
	 * @param start The start index for the result set (0 indexed).
	 * @param end The end index for the result set.
	 * @param listener A listener to handle the result.
	 */
	public static void getSharesByEntity (Activity context, String entityKey, int start, int end, ShareListListener listener) {
		proxy.getSharesByEntity(context, entityKey, start, end, listener);
	}

	/**
	 * Retrieves all share events across all entities.
	 * @param context The current context.
	 * @param start The start index for the result set (0 indexed).
	 * @param end The end index for the result set.
	 * @param listener A listener to handle the result.
	 */
	public static void getSharesByApplication (Activity context, int start, int end, ShareListListener listener) {
		proxy.getSharesByApplication(context, start, end, listener);
	}

	/**
	 * Creates a simple Socialize Share object.
	 * NOTE: This does NOT perform any actual sharing (propagation).  It is used to simply record the fact that a share is taking place.
	 * This is useful when you want to utilize the auto-generated entity links returned in the propagation info response to post directly
	 * to Facebook or Twitter.
	 * @param context The current context.
	 * @param entity The entity to be shared.
	 * @param shareOptions Options for the share allowing text to be specified.
	 * @param listener A listener to handle the result.
	 * @param networks The Social Networks you intend to share to.
	 */
	public static void registerShare(Activity context, Entity entity, ShareOptions shareOptions, ShareAddListener listener, SocialNetwork...networks)  {
		proxy.registerShare(context, entity, shareOptions, listener, networks);
	}

	/**
	 * Determines if the current device is capable of sharing via email.
	 * @param context The current context.
	 * @return True if the device is capable of sharing via email, false otherwise.
	 */
	public static boolean canShareViaEmail(Activity context) {
		return proxy.canShareViaEmail(context);
	}

	/**
	 * Determines if the current device is capable of sharing via SMS.
	 * @param context The current context.
	 * @return True if the device is capable of sharing via SMS, false otherwise.
	 */
	public static boolean canShareViaSMS(Activity context) {
		return proxy.canShareViaSMS(context);
	}
}


/*
 * Copyright (c) 2012 Socialize Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package com.socialize.demo.implementations.entity;

import android.os.Bundle;
import com.socialize.EntityUtils;
import com.socialize.demo.SDKDemoActivity;
import com.socialize.entity.Entity;
import com.socialize.error.SocializeException;
import com.socialize.listener.entity.EntityGetListener;

/**
 * @author Jason Polites
 *
 */
public class GetEntityByKeyActivity extends SDKDemoActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		entryText.setText(entity.getKey());
	}

	/* (non-Javadoc)
	 * @see com.socialize.demo.DemoActivity#executeDemo()
	 */
	@Override
	public void executeDemo(final String text) {

		EntityUtils.getEntity(this, text, new EntityGetListener() {
			@Override
			public void onGet(Entity entity) {
				handleBasicSocializeResult(entity);
			}

			@Override
			public void onError(SocializeException error) {
				if(isNotFoundError(error)) {
					handleResult("No entity found with key [" +
							text +
							"]");
				}
				else {
					handleError(GetEntityByKeyActivity.this, error);
				}
			}
		});
	}

	@Override
	public boolean isTextEntryRequired() {
		return true;
	}

	/* (non-Javadoc)
	 * @see com.socialize.demo.DemoActivity#getButtonText()
	 */
	@Override
	public String getButtonText() {
		return "Get Entity by Key";
	}
}


/*
 * Copyright (c) 2012 Socialize Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package com.socialize.ui.profile;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import com.socialize.util.DeviceUtils;

/**
 * @author Jason Polites
 *
 */
public class DefaultProfileImageContextMenu implements ProfileImageContextMenu {

	private Activity context;
	private DeviceUtils deviceUtils;

	public DefaultProfileImageContextMenu(Activity context) {
		super();
		this.context = context;
	}

	/* (non-Javadoc)
	 * @see com.socialize.ui.profile.ProfileImageContextMenu#show()
	 */
	@Override
	public void show() {

		if(deviceUtils != null && deviceUtils.hasCamera()) {
			final String items[] = {"From Gallery", "From Camera"};

			AlertDialog.Builder ab=new AlertDialog.Builder(context);
			ab.setTitle("New Profile Picture");
			ab.setItems(items, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface d, int choice) {
					if (choice == 0) {
						launchGallery();
					}
					else if (choice == 1) {
						launchCamera();
					}
				}
			});

			ab.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.cancel();
				}
			});

			ab.show();
		}
		else {
			launchGallery();
		}
	}

	protected void launchGallery() {
//		Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		Intent intent = new Intent();
		intent.setType("image/*");
		intent.setAction(Intent.ACTION_GET_CONTENT);

		if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB){
			intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
		}

		context.startActivityForResult(Intent.createChooser(intent, "Select Picture"), ProfileActivity.GALLERY_PIC_REQUEST);
	}

	protected void launchCamera() {
		Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
		context.startActivityForResult(cameraIntent, ProfileActivity.CAMERA_PIC_REQUEST);
	}

	public void setDeviceUtils(DeviceUtils deviceUtils) {
		this.deviceUtils = deviceUtils;
	}
}