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

#include "euterpe/license_wnd.h"
#include "euterpe/app_info.h"
#include "WDL/fileread.h"
#include "WDL/wdlstring.h"

RSE_LicenseWnd::RSE_LicenseWnd()
  : m_hwnd(NULL)
{}

RSE_LicenseWnd::~RSE_LicenseWnd()
{}

HWND RSE_LicenseWnd::Handle() const
{
  return m_hwnd;
}

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

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

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

WDL_DLGRET RSE_LicenseWnd::LicenseWndProc(UINT msg, WPARAM wparam, LPARAM lparam)
{
  switch (msg)
  {
  case WM_INITDIALOG:
    {
      HWND s = GetDlgItem(m_hwnd, IDC_EDIT_LICENSE);

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

      int x = g_ini_file->read_int("license_wnd_x", 0, EUTERPE_NAME);
      int y = g_ini_file->read_int("license_wnd_y", 50, EUTERPE_NAME);
      SetWindowPos(m_hwnd, NULL, x, y, 400, 400, SWP_NOZORDER | SWP_NOACTIVATE);

      WDL_FastString lpath(g_module_path.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);
    }
    break;

#if defined(_WIN32)
    case WM_CTLCOLORSTATIC:
    {
      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);
      }
    }
    break;
#endif

  case WM_DESTROY:
    {
      RECT r;
      GetWindowRect(m_hwnd, &r);

      g_ini_file->write_int("license_wnd_x", r.left, EUTERPE_NAME);
      g_ini_file->write_int("license_wnd_y", r.top, EUTERPE_NAME);

      m_hwnd = NULL;
    }
    break;
  case WM_SIZE:
    {
      if (wparam != SIZE_MINIMIZED)
      {
        m_resize.onResize();
      }
    }
    break;
  case WM_MOVE:
    {

    }
    break;
  case WM_COMMAND:
    {
      switch(LOWORD(wparam))
      {
      case IDCANCEL:
        {
          DestroyWindow(m_hwnd);
        }
        break;
      }
    }
    break;
  }

  return 0;
}
