/*****************************************************************************
Open Source MIT License

Copyright (c) 2017 Matthew Ahmed

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.
*****************************************************************************/

// MainWin.cpp: implementation of the CMainWin class.
//
//////////////////////////////////////////////////////////////////////

#include "Headers.h"
#include "Settings.h"
#include "MainWin.h"
#include "Resource.h"
#include "MinDlg.h"
#include "Tray.h"

CMainWin * pMain;

LRESULT APIENTRY MainWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	return pMain->OwnProc(hWnd, message, wParam, lParam);
}

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CMainWin::CMainWin(HINSTANCE hInst, CSettings * pSet,
												LPCTSTR sCapt1, LPCTSTR sCapt2)
	: ZWin(hInst, sCapt1, sCapt2, NULL)
{
	ini = pSet;
	pMain = this;
	m_pTray = NULL;
}

CMainWin::~CMainWin()
{
}

BOOL CMainWin::Create(LPCTSTR sClassName, INT nShow)
{
	WNDCLASS  wc;

	wc.style = 0;
//	wc.lpfnWndProc = (WNDPROC) wproc; //
//	wc.lpfnWndProc =  this->OwnProc;
	wc.lpfnWndProc = (WNDPROC) MainWndProc;
	wc.cbClsExtra = 0;
	wc.cbWndExtra = 0;
	wc.hInstance = m_hInst;
	wc.hIcon = LoadIcon(m_hInst, MAKEINTRESOURCE(IDI_MAIN));
	wc.hCursor = LoadCursor(0, IDC_ARROW);
	wc.hbrBackground = (HBRUSH) GetStockObject(WHITE_BRUSH);
	wc.lpszMenuName =  MAKEINTRESOURCE(IDR_MAINMENU);
	wc.lpszClassName = sClassName;

	if (!RegisterClass(&wc)) return fnErr("RegisterClass failed");


	m_hWnd = CreateWindow(sClassName,          // Match RegisterClass() name.
											m_sCaptLong,           // Text for window title bar.
											WS_OVERLAPPEDWINDOW,   // Window style.
											CW_USEDEFAULT,    // horizontal position.
											CW_USEDEFAULT,    // vertical position.
											CW_USEDEFAULT,    // width.
											CW_USEDEFAULT,    // height.
											(HWND) NULL,      // Overlapped windows have no parent.
											(HMENU) NULL,     // Use the window class menu.
											m_hInst,          // This instance owns this window.
											(LPVOID) NULL     // Pointer not needed.
											);

    if (!m_hWnd) return fnErr("CreateWindow failed");
		// HERE, WINDOW CREATED, CAN USE m_hWnd

		CenterWnd();

		////- Add initial ops either here or in case : WMU_INIT
    ////- Uncomment this & OnIdmDlg in case WMU_INIT if dlg app w hidden main
		// PostMessage(m_hWnd, WMU_INIT, 0, 0);

		if (!fnShowTray()) return FALSE;  ////- DELETE IF NOT TRAY APP

    ShowWindow(m_hWnd, nShow); // For tray app, nShow usually SW_HIDE
    UpdateWindow(m_hWnd);
		return TRUE;
}

LRESULT CMainWin::OwnProc(HWND hWnd, UINT uMsg, WPARAM wP, LPARAM lP)
{
	switch (uMsg)
	{

		case WM_CREATE:

			// Stuff to do before hWnd visible (hWnd still NULL here)
			// PostMessage(m_hWnd, WMU_INIT, ..) after CreateWindow if need hWnd
			// return -1 here to destroy window

			break;

		case WMU_INIT :
      ////- Uncomment this & PostMessage in Create if dlg app w hidden main
      // OnIdmDlg();

			break;

		////- IF NO TRAY DELETE NEXT 2 cases,
		////- & tray menu WM_COMMAND cases,
		////- and sdelete in WM_DESTROY
		WTAKEMSGPARM(WMU_TRAYMSG, m_pTray->MsgHandler);
		WTAKEMSG(WMU_SHOWTRAYMENU, m_pTray->ShowMenu);
		
		case WM_COMMAND:    // message: command from application menu
			switch (LOWORD(wP))
			{
				WTAKECMD(IDM_DLG, OnIdmDlg);

				////- SUBSTITUTE HANDLERS FOR WHAT DOESN'T GET DELETED BELOW

				case IDM_ITEM:
					MB("IDM_ITEM");
					break;

				case IDM_TRAY: // toggle on off

					if (m_pTray)
          {
            m_pTray->DeleteTrayIcon();
//            if (!sdelete(m_pTray))
//              fnErr("Error removing tray icon");
            delete m_pTray;
            m_pTray = NULL;
          }
          else fnShowTray();

					//if (!sdelete(m_pTray))
					//	fnShowTray();
					break;

				case IDM_CLOSE : // Tray menu msg, i.e. close tray, not app
//					sdelete(m_pTray);
					if (m_pTray)
          {
            m_pTray->DeleteTrayIcon();
            delete m_pTray;
            m_pTray = NULL;
          }
					break;

				case IDM_EXIT : // Tray menu msg
					PostMessage(m_hWnd, WM_CLOSE, 0, 0);
					break;

				default:
					return DefWindowProc(hWnd, uMsg, wP, lP);

			}	// END switch (wParam)
			break; // Redundant?  No, break from outer switch


		case WM_DESTROY:
//			sdelete(m_pTray);
			if (m_pTray)
      {
        m_pTray->DeleteTrayIcon();
        delete m_pTray;
        m_pTray = NULL;
      }
			PostQuitMessage(0);
			break;

		default:
			return DefWindowProc(hWnd, uMsg, wP, lP);

	}  // END switch (message)

	return 0;

}

void CMainWin::OnIdmDlg()
{
	CMinDlg* pDlg = NULL;
	pDlg = new CMinDlg(m_hInst, ini, m_sCapt, NULL, this);
	if (!pDlg) RET_V("Error creating dialog")
	pDlg->Run();
}

////- IF NO TRAY DELETE (and include & m_pTray)
BOOL CMainWin::fnShowTray()
{
	m_pTray = new CTray(m_hInst, ini, m_sCapt, NULL,
											this, IDI_TRAY, IDR_TRAYMENU);
	if (!m_pTray) return fnErr("Error allocating CTray");
	if (!m_pTray->AddTrayIcon())
		return fnErr("Error creating tray icon");
	return TRUE;
}
