//  ======================================================================
//               THIS IMPLEMENTATION WRITTEN BY KK - SPRING 1998
//  ======================================================================

#include "winplus.h"
#pragma  hdrstop

CMenu::CMenu()
{
  bLoadedFromResource=FALSE;
  hmenumain=NULL;
  iNextPopupPtr=0;
  memset(hmenupopup,0,MAX_POPUP_ITEM*sizeof(HMENU));
}

CMenu::~CMenu()
{
  if(hmenumain) Destroy();
}

void CMenu::Create(int iPopups)
{
  int i;
  if(hmenumain) Destroy();
  if((iPopups<=0)||(iPopups>=MAX_POPUP_ITEM)) return;
  hmenumain = ::CreateMenu();
  for(i=0; i<iPopups; i++) hmenupopup[i] = ::CreatePopupMenu();
  iNextPopupPtr=0;
  if(win) ::SetMenu(win->GetWnd(),hmenumain);
}

void CMenu::NextPopup(LPSTR lpItemName)
{
  if(iNextPopupPtr>=MAX_POPUP_ITEM) return;
  ::AppendMenu(hmenumain,MF_ENABLED|MF_POPUP,
    (UINT)hmenupopup[iNextPopupPtr], lpItemName);
  iNextPopupPtr++;
  if(win) ::DrawMenuBar(win->GetWnd());
}

void CMenu::AppendTo(int iPopup, UINT fuFlags, UINT idNewItem,
  LPCSTR lpNewItem)
{
  ::AppendMenu(hmenupopup[iPopup], fuFlags, idNewItem, lpNewItem);
  if(win) ::DrawMenuBar(win->GetWnd());
}

void CMenu::Set(CWindowBase &cWnd)
{
  win=&cWnd;
  if(hmenumain)
  {
    ::SetMenu(win->GetWnd(),hmenumain);
    if(win->bCreated) ::DrawMenuBar(win->GetWnd());
  }
}

void CMenu::Destroy()
{
  if(hmenumain)
  {
    if(!bLoadedFromResource)
    {
      for(int i=0; i<MAX_POPUP_ITEM; i++)
        if(hmenupopup[i])
        {
          ::DestroyMenu(hmenupopup[i]);
          hmenupopup[i]=NULL;
        }
      ::DestroyMenu(hmenumain);
      hmenumain=NULL;
    }
    else
    {
      ::DestroyMenu(hmenumain);
      bLoadedFromResource=FALSE;
    }
  }
}

void CMenu::Load(LPSTR lpResource)
{
  if(win)
  {
    if(hmenumain) Destroy();
    hmenumain= ::LoadMenu(win->GetInstance(), lpResource);
    if(hmenumain)
    {
      ::SetMenu(win->GetWnd(), hmenumain);
      bLoadedFromResource=TRUE;
    }
    ::SetMenu(win->GetWnd(),hmenumain);
  }
}

void CMenu::Load(int iResource)
{
  CMenu::Load(MAKEINTRESOURCE(iResource));
}

void CMenu::EnableItem(UINT idEnableItem, UINT uEnable)
{
  ::EnableMenuItem(hmenumain, idEnableItem, uEnable);
}

void CMenu::CheckItem(UINT idCheckItem, UINT uCheck)
{
  ::CheckMenuItem(hmenumain, idCheckItem, uCheck);
}

