/*
 * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
 */
package com.sun.glass.ui;

import com.sun.glass.ui.delegate.MenuBarDelegate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class MenuBar {
    final private MenuBarDelegate delegate;

    long getNativeMenu() {
        return delegate.getNativeMenu();
    }

    private final List<Menu> menus = new ArrayList<Menu>();

    protected MenuBar() {
        delegate = PlatformFactory.getPlatformFactory().createMenuBarDelegate(this);
        if (!delegate.createMenuBar()) {
            throw new RuntimeException("MenuBar creation error.");
        }
    }

    public void add(Menu menu) {
        insert(menu, menus.size());
    }

    public void insert(Menu menu, int pos) {
        synchronized (menus) {
            if (delegate.insert(menu.getDelegate(), pos)) {
                menus.add(pos, menu);
            }
        }
    }

    public void remove(int pos) {
        synchronized (menus) {
            Menu menu = menus.get(pos);
            if (delegate.remove(menu.getDelegate(), pos)) {
                menus.remove(pos);
            }
        }
    }

    public void remove(Menu menu) {
        synchronized (menus) {
            int pos = menus.indexOf(menu);
            if (pos >= 0) {
                if (delegate.remove(menu.getDelegate(), pos)) {
                    menus.remove(pos);
                }
            } else {
                // throw some exception?
            }
        }
    }

    public List<Menu> getMenus() {
        return Collections.unmodifiableList(menus);
    }

    // package private
    MenuBarDelegate getDelegate() {
        return delegate;
    }
}
