/*
 * Copyright (C) 2006 The Android Open Source Project
 *
 * 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.
 */

///<reference path="../../android/app/Activity.ts"/>
///<reference path="../../android/view/KeyEvent.ts"/>
///<reference path="../../android/view/MenuItem.ts"/>

module android.view {
import Activity = android.app.Activity;
import KeyEvent = android.view.KeyEvent;
import MenuItem = android.view.MenuItem;
import ArrayList = java.util.ArrayList;
import Context = android.content.Context;

/**
 * Interface for managing the items in a menu.
 * <p>
 * By default, every Activity supports an options menu of actions or options.
 * You can add items to this menu and handle clicks on your additions. The
 * easiest way of adding menu items is inflating an XML file into the
 * {@link Menu} via {@link MenuInflater}. The easiest way of attaching code to
 * clicks is via {@link Activity#onOptionsItemSelected(MenuItem)} and
 * {@link Activity#onContextItemSelected(MenuItem)}.
 * <p>
 * Different menu types support different features:
 * <ol>
 * <li><b>Context menus</b>: Do not support item shortcuts and item icons.
 * <li><b>Options menus</b>: The <b>icon menus</b> do not support item check
 * marks and only show the item's
 * {@link MenuItem#setTitleCondensed(CharSequence) condensed title}. The
 * <b>expanded menus</b> (only available if six or more menu items are visible,
 * reached via the 'More' item in the icon menu) do not show item icons, and
 * item check marks are discouraged.
 * <li><b>Sub menus</b>: Do not support item icons, or nested sub menus.
 * </ol>
 *
 * <div class="special reference">
 * <h3>Developer Guides</h3>
 * <p>For more information about creating menus, read the
 * <a href="{@docRoot}guide/topics/ui/menus.html">Menus</a> developer guide.</p>
 * </div>
 */
export class Menu {

    /**
     * Contains all of the items for this menu
     */
    private mItems = new ArrayList<MenuItem>();
    private mVisibleItems = new ArrayList<MenuItem>();

    /**
     * Callback that will receive the various menu-related events generated by this class. Use
     * getCallback to get a reference to the callback.
     */
    private mCallback:Menu.Callback;

    private mContext:Context;

    constructor(context:Context) {
        this.mContext = context;
    }

    getContext():Context {
        return this.mContext;
    }

    /**
     * Add a new item to the menu. This item displays the given title for its
     * label.
     * 
     * @param title The text to display for the item.
     * @return The newly added menu item.
     */
    add(title:string):MenuItem ;

    /**
     * Add a new item to the menu. This item displays the given title for its
     * label.
     *
     * @param groupId The group identifier that this item should be part of.
     *        This can be used to define groups of items for batch state
     *        changes. Normally use {@link #NONE} if an item should not be in a
     *        group.
     * @param itemId Unique item ID. Use {@link #NONE} if you do not need a
     *        unique ID.
     * @param order The order for the item. Use {@link #NONE} if you do not care
     *        about the order. See {@link MenuItem#getOrder()}.
     * @param title The text to display for the item.
     * @return The newly added menu item.
     */
    add(groupId:number, itemId:number, order:number, title:string):MenuItem ;
    add(...args):MenuItem {
        if(args.length==1) return this.addInternal(0, 0, 0, args[0]);
        return this.addInternal(args[0], args[1], args[2], args[3]);
    }

    ///**
    // * Add a new item to the menu. This item displays the given title for its
    // * label.
    // *
    // * @param titleRes Resource identifier of title string.
    // * @return The newly added menu item.
    // */
    //add(titleRes:number):MenuItem ;

    ///**
    // * Variation on {@link #add(int, int, int, CharSequence)} that takes a
    // * string resource identifier instead of the string itself.
    // *
    // * @param groupId The group identifier that this item should be part of.
    // *        This can also be used to define groups of items for batch state
    // *        changes. Normally use {@link #NONE} if an item should not be in a
    // *        group.
    // * @param itemId Unique item ID. Use {@link #NONE} if you do not need a
    // *        unique ID.
    // * @param order The order for the item. Use {@link #NONE} if you do not care
    // *        about the order. See {@link MenuItem#getOrder()}.
    // * @param titleRes Resource identifier of title string.
    // * @return The newly added menu item.
    // */
    //add(groupId:number, itemId:number, order:number, titleRes:number):MenuItem ;

    /**
     * Adds an item to the menu.  The other add methods funnel to this.
     */
    private addInternal(group:number, id:number, categoryOrder:number, title:string):MenuItem  {
        const ordering:number = 0;//MenuBuilder.getOrdering(categoryOrder);
        const item:MenuItem = new MenuItem(this, group, id, categoryOrder, ordering, title);
        //if (this.mCurrentMenuInfo != null) {
        //    // Pass along the current menu info
        //    item.setMenuInfo(this.mCurrentMenuInfo);
        //}
        this.mItems.add(/*MenuBuilder.findInsertIndex(this.mItems, ordering), */item);
        this.onItemsChanged(true);
        return item;
    }
    ///**
    // * Add a new sub-menu to the menu. This item displays the given title for
    // * its label. To modify other attributes on the submenu's menu item, use
    // * {@link SubMenu#getItem()}.
    // *
    // * @param title The text to display for the item.
    // * @return The newly added sub-menu
    // */
    //addSubMenu(title:string):SubMenu ;
    //
    ///**
    // * Add a new sub-menu to the menu. This item displays the given title for
    // * its label. To modify other attributes on the submenu's menu item, use
    // * {@link SubMenu#getItem()}.
    // *
    // * @param titleRes Resource identifier of title string.
    // * @return The newly added sub-menu
    // */
    //addSubMenu(titleRes:number):SubMenu ;
    //
    ///**
    // * Add a new sub-menu to the menu. This item displays the given
    // * <var>title</var> for its label. To modify other attributes on the
    // * submenu's menu item, use {@link SubMenu#getItem()}.
    // *<p>
    // * Note that you can only have one level of sub-menus, i.e. you cannnot add
    // * a subMenu to a subMenu: An {@link UnsupportedOperationException} will be
    // * thrown if you try.
    // *
    // * @param groupId The group identifier that this item should be part of.
    // *        This can also be used to define groups of items for batch state
    // *        changes. Normally use {@link #NONE} if an item should not be in a
    // *        group.
    // * @param itemId Unique item ID. Use {@link #NONE} if you do not need a
    // *        unique ID.
    // * @param order The order for the item. Use {@link #NONE} if you do not care
    // *        about the order. See {@link MenuItem#getOrder()}.
    // * @param title The text to display for the item.
    // * @return The newly added sub-menu
    // */
    //addSubMenu(groupId:number, itemId:number, order:number, title:string):SubMenu ;
    //
    ///**
    // * Variation on {@link #addSubMenu(int, int, int, CharSequence)} that takes
    // * a string resource identifier for the title instead of the string itself.
    // *
    // * @param groupId The group identifier that this item should be part of.
    // *        This can also be used to define groups of items for batch state
    // *        changes. Normally use {@link #NONE} if an item should not be in a group.
    // * @param itemId Unique item ID. Use {@link #NONE} if you do not need a unique ID.
    // * @param order The order for the item. Use {@link #NONE} if you do not care about the
    // *        order. See {@link MenuItem#getOrder()}.
    // * @param titleRes Resource identifier of title string.
    // * @return The newly added sub-menu
    // */
    //addSubMenu(groupId:number, itemId:number, order:number, titleRes:number):SubMenu ;
    //
    ///**
    // * Add a group of menu items corresponding to actions that can be performed
    // * for a particular Intent. The Intent is most often configured with a null
    // * action, the data that the current activity is working with, and includes
    // * either the {@link Intent#CATEGORY_ALTERNATIVE} or
    // * {@link Intent#CATEGORY_SELECTED_ALTERNATIVE} to find activities that have
    // * said they would like to be included as optional action. You can, however,
    // * use any Intent you want.
    // *
    // * <p>
    // * See {@link android.content.pm.PackageManager#queryIntentActivityOptions}
    // * for more * details on the <var>caller</var>, <var>specifics</var>, and
    // * <var>intent</var> arguments. The list returned by that function is used
    // * to populate the resulting menu items.
    // *
    // * <p>
    // * All of the menu items of possible options for the intent will be added
    // * with the given group and id. You can use the group to control ordering of
    // * the items in relation to other items in the menu. Normally this function
    // * will automatically remove any existing items in the menu in the same
    // * group and place a divider above and below the added items; this behavior
    // * can be modified with the <var>flags</var> parameter. For each of the
    // * generated items {@link MenuItem#setIntent} is called to associate the
    // * appropriate Intent with the item; this means the activity will
    // * automatically be started for you without having to do anything else.
    // *
    // * @param groupId The group identifier that the items should be part of.
    // *        This can also be used to define groups of items for batch state
    // *        changes. Normally use {@link #NONE} if the items should not be in
    // *        a group.
    // * @param itemId Unique item ID. Use {@link #NONE} if you do not need a
    // *        unique ID.
    // * @param order The order for the items. Use {@link #NONE} if you do not
    // *        care about the order. See {@link MenuItem#getOrder()}.
    // * @param caller The current activity component name as defined by
    // *        queryIntentActivityOptions().
    // * @param specifics Specific items to place first as defined by
    // *        queryIntentActivityOptions().
    // * @param intent Intent describing the kinds of items to populate in the
    // *        list as defined by queryIntentActivityOptions().
    // * @param flags Additional options controlling how the items are added.
    // * @param outSpecificItems Optional array in which to place the menu items
    // *        that were generated for each of the <var>specifics</var> that were
    // *        requested. Entries may be null if no activity was found for that
    // *        specific action.
    // * @return The number of menu items that were added.
    // *
    // * @see #FLAG_APPEND_TO_GROUP
    // * @see MenuItem#setIntent
    // * @see android.content.pm.PackageManager#queryIntentActivityOptions
    // */
    //addIntentOptions(groupId:number, itemId:number, order:number, caller:ComponentName, specifics:Intent[], intent:Intent, flags:number, outSpecificItems:MenuItem[]):number ;

    /**
     * Remove the item with the given identifier.
     *
     * @param id The item to be removed.  If there is no item with this
     *           identifier, nothing happens.
     */
    removeItem(id:number):void {
        this.removeItemAtInt(this.findItemIndex(id), true);
    }

    /**
     * Remove all items in the given group.
     *
     * @param groupId The group to be removed.  If there are no items in this
     *           group, nothing happens.
     */
    removeGroup(groupId:number):void {
        const i:number = this.findGroupIndex(groupId);
        if (i >= 0) {
            const maxRemovable:number = this.mItems.size() - i;
            let numRemoved:number = 0;
            while ((numRemoved++ < maxRemovable) && (this.mItems.get(i).getGroupId() == groupId)) {
                // Don't force update for each one, this method will do it at the end
                this.removeItemAtInt(i, false);
            }
            // Notify menu views
            this.onItemsChanged(true);
        }
    }


    /**
     * Remove the item at the given index and optionally forces menu views to update.
     *
     * @param index                     The index of the item to be removed. If this index is
     *                                  invalid an exception is thrown.
     * @param updateChildrenOnMenuViews Whether to force update on menu views. Please make sure you
     *                                  eventually call this after your batch of removals.
     */
    private removeItemAtInt(index:number, updateChildrenOnMenuViews:boolean):void  {
        if ((index < 0) || (index >= this.mItems.size())) {
            return;
        }
        this.mItems.remove(index);
        if (updateChildrenOnMenuViews) {
            this.onItemsChanged(true);
        }
    }

    /**
     * Remove all existing items from the menu, leaving it empty as if it had
     * just been created.
     */
    clear():void {
        this.mItems.clear();
        this.onItemsChanged(true);
    }

    ///**
    // * Control whether a particular group of items can show a check mark.  This
    // * is similar to calling {@link MenuItem#setCheckable} on all of the menu items
    // * with the given group identifier, but in addition you can control whether
    // * this group contains a mutually-exclusive set items.  This should be called
    // * after the items of the group have been added to the menu.
    // *
    // * @param group The group of items to operate on.
    // * @param checkable Set to true to allow a check mark, false to
    // *                  disallow.  The default is false.
    // * @param exclusive If set to true, only one item in this group can be
    // *                  checked at a time; checking an item will automatically
    // *                  uncheck all others in the group.  If set to false, each
    // *                  item can be checked independently of the others.
    // *
    // * @see MenuItem#setCheckable
    // * @see MenuItem#setChecked
    // */
    //setGroupCheckable(group:number, checkable:boolean, exclusive:boolean):void ;

    /**
     * Show or hide all menu items that are in the given group.
     *
     * @param group The group of items to operate on.
     * @param visible If true the items are visible, else they are hidden.
     *
     * @see MenuItem#setVisible
     */
    setGroupVisible(group:number, visible:boolean):void {
        const N:number = this.mItems.size();
        // We handle the notification of items being changed ourselves, so we use setVisibleInt
        // rather than setVisible and at the end notify of items being changed
        let changedAtLeastOneItem:boolean = false;
        for (let i:number = 0; i < N; i++) {
            let item:MenuItem = this.mItems.get(i);
            if (item.getGroupId() == group) {
                if (item.setVisible(visible)) {//androidui modify: setVisibleInt
                    changedAtLeastOneItem = true;
                }
            }
        }
        if (changedAtLeastOneItem) {
            this.onItemsChanged(true);
        }
    }

    /**
     * Enable or disable all menu items that are in the given group.
     *
     * @param group The group of items to operate on.
     * @param enabled If true the items will be enabled, else they will be disabled.
     *
     * @see MenuItem#setEnabled
     */
    setGroupEnabled(group:number, enabled:boolean):void {
        const N:number = this.mItems.size();
        for (let i:number = 0; i < N; i++) {
            let item:MenuItem = this.mItems.get(i);
            if (item.getGroupId() == group) {
                item.setEnabled(enabled);
            }
        }
    }

    /**
     * Return whether the menu currently has item items that are visible.
     *
     * @return True if there is one or more item visible,
     *         else false.
     */
    hasVisibleItems():boolean {
        const size:number = this.size();
        for (let i:number = 0; i < size; i++) {
            let item:MenuItem = this.mItems.get(i);
            if (item.isVisible()) {
                return true;
            }
        }
        return false;
    }

    /**
     * Return the menu item with a particular identifier.
     *
     * @param id The identifier to find.
     *
     * @return The menu item object, or null if there is no item with
     *         this identifier.
     */
    findItem(id:number):MenuItem {
        const size:number = this.size();
        for (let i:number = 0; i < size; i++) {
            let item:MenuItem = this.mItems.get(i);
            if (item.getItemId() == id) {
                return item;
            }
            //else if (item.hasSubMenu()) {
            //    let possibleItem:MenuItem = item.getSubMenu().findItem(id);
            //    if (possibleItem != null) {
            //        return possibleItem;
            //    }
            //}
        }
        return null;
    }

    findItemIndex(id:number):number  {
        const size:number = this.size();
        for (let i:number = 0; i < size; i++) {
            let item:MenuItem = this.mItems.get(i);
            if (item.getItemId() == id) {
                return i;
            }
        }
        return -1;
    }

    findGroupIndex(group:number, start=0):number  {
        const size:number = this.size();
        if (start < 0) {
            start = 0;
        }
        for (let i:number = start; i < size; i++) {
            const item:MenuItem = this.mItems.get(i);
            if (item.getGroupId() == group) {
                return i;
            }
        }
        return -1;
    }


    /**
     * Get the number of items in the menu.  Note that this will change any
     * times items are added or removed from the menu.
     *
     * @return The item count.
     */
    size():number {
        return this.mItems.size();
    }

    /**
     * Gets the menu item at the given index.
     * 
     * @param index The index of the menu item to return.
     * @return The menu item.
     * @exception IndexOutOfBoundsException
     *                when {@code index < 0 || >= size()}
     */
    getItem(index:number):MenuItem {
        return this.mItems.get(index);
    }

    ///**
    // * Closes the menu, if open.
    // */
    //close():void ;
    //
    ///**
    // * Execute the menu item action associated with the given shortcut
    // * character.
    // *
    // * @param keyCode The keycode of the shortcut key.
    // * @param event Key event message.
    // * @param flags Additional option flags or 0.
    // *
    // * @return If the given shortcut exists and is shown, returns
    // *         true; else returns false.
    // *
    // * @see #FLAG_PERFORM_NO_CLOSE
    // */
    //performShortcut(keyCode:number, event:KeyEvent, flags:number):boolean ;
    //
    ///**
    // * Is a keypress one of the defined shortcut keys for this window.
    // * @param keyCode the key code from {@link KeyEvent} to check.
    // * @param event the {@link KeyEvent} to use to help check.
    // */
    //isShortcutKey(keyCode:number, event:KeyEvent):boolean ;
    //
    ///**
    // * Execute the menu item action associated with the given menu identifier.
    // *
    // * @param id Identifier associated with the menu item.
    // * @param flags Additional option flags or 0.
    // *
    // * @return If the given identifier exists and is shown, returns
    // *         true; else returns false.
    // *
    // * @see #FLAG_PERFORM_NO_CLOSE
    // */
    //performIdentifierAction(id:number, flags:number):boolean ;
    //
    ///**
    // * Control whether the menu should be running in qwerty mode (alphabetic
    // * shortcuts) or 12-key mode (numeric shortcuts).
    // *
    // * @param isQwerty If true the menu will use alphabetic shortcuts; else it
    // *                 will use numeric shortcuts.
    // */
    //setQwertyMode(isQwerty:boolean):void ;


    /**
     * Called when an item is added or removed.
     *
     * @param structureChanged true if the menu structure changed, false if only item properties
     *                         changed. (Visibility is a structural property since it affects
     *                         layout.)
     */
    onItemsChanged(structureChanged:boolean):void  {
        //if (!this.mPreventDispatchingItemsChanged) {
        //    if (structureChanged) {
        //        this.mIsVisibleItemsStale = true;
        //        this.mIsActionItemsStale = true;
        //    }
        //    this.dispatchPresenterUpdate(structureChanged);
        //} else {
        //    this.mItemsChangedWhileDispatchPrevented = true;
        //}
    }

    /**
     * Gets the root menu (if this is a submenu, find its root menu).
     *
     * @return The root menu.
     */
    getRootMenu():Menu {
        return this;
    }

    setCallback(cb:Menu.Callback):void  {
        this.mCallback = cb;
    }

    dispatchMenuItemSelected(menu:Menu, item:MenuItem):boolean  {
        return this.mCallback != null && this.mCallback.onMenuItemSelected(menu, item);
    }

    getVisibleItems():ArrayList<MenuItem>  {
        this.mVisibleItems.clear();
        const itemsSize:number = this.mItems.size();
        let item:MenuItem;
        for (let i:number = 0; i < itemsSize; i++) {
            item = this.mItems.get(i);
            if (item.isVisible()) {
                this.mVisibleItems.add(item);
            }
        }
        return this.mVisibleItems;
    }
}

export module Menu{
/**
     * This is the part of an order integer that the user can provide.
     * @hide
     */
export var USER_MASK:number = 0x0000ffff;
/**
     * Bit shift of the user portion of the order integer.
     * @hide
     */
export var USER_SHIFT:number = 0;
/**
     * This is the part of an order integer that supplies the category of the
     * item.
     * @hide
     */
export var CATEGORY_MASK:number = 0xffff0000;
/**
     * Bit shift of the category portion of the order integer.
     * @hide
     */
export var CATEGORY_SHIFT:number = 16;
/**
     * Value to use for group and item identifier integers when you don't care
     * about them.
     */
export var NONE:number = 0;
/**
     * First value for group and item identifier integers.
     */
export var FIRST:number = 1;
// Implementation note: Keep these CATEGORY_* in sync with the category enum
// in attrs.xml
/**
     * Category code for the order integer for items/groups that are part of a
     * container -- or/add this with your base value.
     */
export var CATEGORY_CONTAINER:number = 0x00010000;
/**
     * Category code for the order integer for items/groups that are provided by
     * the system -- or/add this with your base value.
     */
export var CATEGORY_SYSTEM:number = 0x00020000;
/**
     * Category code for the order integer for items/groups that are
     * user-supplied secondary (infrequently used) options -- or/add this with
     * your base value.
     */
export var CATEGORY_SECONDARY:number = 0x00030000;
/**
     * Category code for the order integer for items/groups that are 
     * alternative actions on the data that is currently displayed -- or/add
     * this with your base value.
     */
export var CATEGORY_ALTERNATIVE:number = 0x00040000;
/**
     * Flag for {@link #addIntentOptions}: if set, do not automatically remove
     * any existing menu items in the same group.
     */
export var FLAG_APPEND_TO_GROUP:number = 0x0001;
/**
     * Flag for {@link #performShortcut}: if set, do not close the menu after
     * executing the shortcut.
     */
export var FLAG_PERFORM_NO_CLOSE:number = 0x0001;
/**
     * Flag for {@link #performShortcut(int, KeyEvent, int)}: if set, always
     * close the menu after executing the shortcut. Closing the menu also resets
     * the prepared state.
     */
export var FLAG_ALWAYS_PERFORM_CLOSE:number = 0x0002;

        /**
         * Called by menu to notify of close and selection changes.
         * @hide
         */
        export interface Callback {

            /**
             * Called when a menu item is selected.
             *
             * @param menu The menu that is the parent of the item
             * @param item The menu item that is selected
             * @return whether the menu item selection was handled
             */
            onMenuItemSelected(menu:Menu, item:MenuItem):boolean ;

            ///**
            // * Called when the mode of the menu changes (for example, from icon to expanded).
            // *
            // * @param menu the menu that has changed modes
            // */
            //onMenuModeChange(menu:MenuBuilder):void ;
        }
}

}