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

#include "RSI/license_wnd.h"

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

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

  int x = GetPrivateProfileInt(RSI_NAME, "license_wnd_x", 0, g_inipath.Get());
  int y = GetPrivateProfileInt(RSI_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 RSI_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 RSI_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(RSI_NAME,"license_wnd_x", rleft.Get(), g_inipath.Get());
  WritePrivateProfileString(RSI_NAME,"license_wnd_y", rtop.Get(), g_inipath.Get());
}

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

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

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

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

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

WDL_DLGRET RSI_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;
}
