// Copyright (c) 2021 Giorgos Vougioukas
//
// The license can be found in the LICENSE file.

#include "mnemosyne/license_wnd.h"

void RSM_LicenseWnd::OnInitDialog()
{
  HWND s = GetDlgItem(m_hwnd, IDC_EDIT_LICENSE);

  m_resize.init(m_hwnd);
  m_resize.init_itemhwnd(s);

  int x = GetPrivateProfileInt(MNEMOSYNE_NAME, "license_wnd_x", 0, g_inipath.Get());
  int y = GetPrivateProfileInt(MNEMOSYNE_NAME, "license_wnd_y", 50, g_inipath.Get());
  SetWindowPos(m_hwnd, NULL, x, y, 400, 400, SWP_NOZORDER | SWP_NOACTIVATE);

  WDL_FastString lpath(g_modpath.Get());
  lpath.Append("license.txt");
  WDL_FileRead lfile(lpath.Get());

  WDL_String ltext;
  ltext.SetLen((int)lfile.GetSize());
  lfile.Read(ltext.Get(), (int)lfile.GetSize());

  SetFocus(s);

  SetDlgItemText(m_hwnd, IDC_EDIT_LICENSE, ltext.Get());
  SendMessage(s, EM_SETSEL, -1, 0);
}

#ifdef _WIN32
INT_PTR RSM_LicenseWnd::OnCtlColorStatic()
{
  if((HWND)m_lparam == GetDlgItem(m_hwnd, IDC_EDIT_LICENSE))
  {
    SetBkMode((HDC)m_wparam, TRANSPARENT);
    SetTextColor((HDC)m_wparam, RGB(0, 0, 0));
    return (INT_PTR)((HBRUSH)GetStockObject(WHITE_BRUSH));
    // if edit control is in dialog procedure change LRESULT to INT_PTR
  }
  else // this is some other static control, do not touch it.
  {
    return DefWindowProc(m_hwnd, m_msg, m_wparam, m_lparam);
  }
}
#endif

void RSM_LicenseWnd::OnDestroy()
{
  RECT r;
  GetWindowRect(m_hwnd, &r);

  WDL_FastString rleft, rtop;
  rleft.SetFormatted(32, "%d", r.left);
  rtop.SetFormatted(32, "%d", r.top);

  WritePrivateProfileString(MNEMOSYNE_NAME,"license_wnd_x", rleft.Get(), g_inipath.Get());
  WritePrivateProfileString(MNEMOSYNE_NAME,"license_wnd_y", rtop.Get(), g_inipath.Get());
}

void RSM_LicenseWnd::OnSize()
{
  if (m_wparam != SIZE_MINIMIZED)
  {
    m_resize.onResize();
  }
}

void RSM_LicenseWnd::OnCommand()
{
  switch(LOWORD(m_wparam))
  {
  case IDCANCEL:
    {
      if (g_licwnd) { delete g_licwnd; g_licwnd = NULL; }
    }
    break;
  }
}

WDL_DLGRET RSM_LicenseWnd::LicenseWndProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
{
  RSM_LicenseWnd *self = (RSM_LicenseWnd *)GetWindowLongPtr(hwnd, GWLP_USERDATA);

  if (!self && msg == WM_INITDIALOG)
  {
    SetWindowLongPtr(hwnd, GWLP_USERDATA, lparam);
    self = (RSM_LicenseWnd *)lparam;
    self->m_hwnd = hwnd;
  }

  if (WDL_likely(self))
  {
    return self->LicenseWndLoop(msg, wparam, lparam);
  }
  else
  {
    return 0;
  }
}

WDL_DLGRET RSM_LicenseWnd::LicenseWndLoop(UINT msg, WPARAM wparam, LPARAM lparam)
{
  m_msg = msg;
  m_wparam = wparam;
  m_lparam = lparam;

  switch (msg)
  {
    case WM_INITDIALOG: OnInitDialog(); break;
#ifdef _WIN32
    case WM_CTLCOLORSTATIC: OnCtlColorStatic(); break;
#endif
    case WM_DESTROY: OnDestroy(); break;
    case WM_SIZE: OnSize(); break;
    case WM_COMMAND: OnCommand(); break;
  }

  return 0;
}
