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

#include "thalia/license_wnd.h"

void THA_LicenseWnd::OnInitDialog(WPARAM wparam, LPARAM lparam)
{
  HWND s = GetDlgItem(m_hwnd, IDC_EDIT_LICENSE);

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

  int x = GetPrivateProfileInt(THA_NAME, "license_wnd_x", 0, g_inipath.Get());
  int y = GetPrivateProfileInt(THA_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 THA_LicenseWnd::OnCtlColorStatic(UINT msg, WPARAM wparam, LPARAM lparam)
{
  if((HWND)lparam == GetDlgItem(m_hwnd, IDC_EDIT_LICENSE))
  {
    SetBkMode((HDC)wparam, TRANSPARENT);
    SetTextColor((HDC)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, msg, wparam, lparam);
  }
}
#endif

void THA_LicenseWnd::OnDestroy(WPARAM wparam, LPARAM lparam)
{
  RECT r;
  GetWindowRect(m_hwnd, &r);

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

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

void THA_LicenseWnd::OnSize(WPARAM wparam, LPARAM lparam)
{
  if (wparam != SIZE_MINIMIZED)
  {
    m_resize.onResize();
  }
}

void THA_LicenseWnd::OnCommand(WPARAM wparam, LPARAM lparam)
{
  switch(LOWORD(wparam))
  {
  case IDCANCEL:
    {
      if (g_licwnd) { delete g_licwnd; g_licwnd = NULL; }
    }
    break;
  }
}

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

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

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

WDL_DLGRET THA_LicenseWnd::LicenseWndLoop(UINT msg, WPARAM wparam, LPARAM lparam)
{
  switch (msg)
  {
    case WM_INITDIALOG: OnInitDialog(wparam, lparam); break;
#ifdef _WIN32
    case WM_CTLCOLORSTATIC: OnCtlColorStatic(msg, wparam, lparam); break;
#endif
    case WM_DESTROY: OnDestroy(wparam, lparam); break;
    case WM_SIZE: OnSize(wparam, lparam); break;
    case WM_COMMAND: OnCommand(wparam, lparam); break;
  }

  return 0;
}
