package org.arkiwi.app.utility;

import org.arkiwi.app.adapter.AdapterIconMenu;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.res.Resources;

public class IcoCtxMenu implements DialogInterface.OnCancelListener, 
										DialogInterface.OnDismissListener{
	@SuppressWarnings("unused")
	private static final String LOG_TAG = "IconContextMenu";
	
	private AdapterIconMenu menuAdapter = null;
	private Activity parentActivity = null;
	private int dialogId = 0;
	
	private IconContextMenuOnClickListener clickHandler = null; 
	
	
	/**
	 * constructor
	 * @param parent
	 * @param id
	 */
	public IcoCtxMenu(Activity parent, int id) {
		this.parentActivity = parent;
		this.dialogId = id;
		
		menuAdapter = new AdapterIconMenu(parentActivity);
	}
	
	/**
	 * Add menu item
	 * @param menuItem
	 */
	public void addItem(Resources res, CharSequence title,
			int imageResourceId, int actionTag) {
		menuAdapter.addItem(new IconContextMenuItem(res, title, imageResourceId, actionTag));
	}
	
	public void addItem(Resources res, int textResourceId,
			int imageResourceId, int actionTag) {
		menuAdapter.addItem(new IconContextMenuItem(res, textResourceId, imageResourceId, actionTag));
	}
	
	/**
	 * Set menu onclick listener
	 * @param listener
	 */
	public void setOnClickListener(IconContextMenuOnClickListener listener) {
		clickHandler = listener;
	}
	
	/**
	 * Create menu
	 * @return
	 */
	public Dialog createMenu(String menuItitle, int icon) {
		final AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity);
        builder.setTitle(menuItitle);
        builder.setIcon(icon);
        builder.setAdapter(menuAdapter, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialoginterface, int i) {
				IconContextMenuItem item = (IconContextMenuItem) menuAdapter.getItem(i);
				
				if (clickHandler != null) {
					clickHandler.onClick(item.actionTag);
				}
			}
		});

        builder.setInverseBackgroundForced(true);

        AlertDialog dialog = builder.create();
        dialog.setOnCancelListener(this);
        dialog.setOnDismissListener(this);
        return dialog;
	}
	
	public void onCancel(DialogInterface dialog) {
        cleanup();
    }

    public void onDismiss(DialogInterface dialog) {
    	cleanup();
    }
   
    private void cleanup() {
    	//Log.d(LOG_TAG,"remove dialog");
    	parentActivity.removeDialog(dialogId);
    }
	
    /**
     * IconContextMenu On Click Listener interface
     */
    public interface IconContextMenuOnClickListener {
		public abstract void onClick(int menuId);
    }
}