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

#include "euterpe/changelog_wnd.h"
#include "euterpe/app_info.h"

#define PREVIEW_EDITOR_TIMER 100
#define PREVIEW_EDITOR_TIMER_MS 50

static win32CursesCtx s_curses_ctx;

RSE_ChangeLogWnd::RSE_ChangeLogWnd()
  : m_hwnd(NULL)
  , m_preview(&s_curses_ctx)
{}

RSE_ChangeLogWnd::~RSE_ChangeLogWnd()
{}

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

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

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

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

WDL_DLGRET RSE_ChangeLogWnd::ChangelogWndProc(UINT msg, WPARAM wparam, LPARAM lparam)
{
  switch (msg)
  {
  case WM_INITDIALOG:
    {
      HWND cc = GetDlgItem(m_hwnd, IDC_CUSTOM1);
      curses_setWindowContext(cc, &s_curses_ctx);

      m_resize.init(m_hwnd);
      m_resize.init_itemhwnd(cc, 0.0f, 0.0f, 1.0f, 1.0f);

      int x = g_ini_file->read_int("changelog_wnd_x", 0, EUTERPE_NAME);
      int y = g_ini_file->read_int("changelog_wnd_y", 50, EUTERPE_NAME);
#if defined(_WIN32)
      SetWindowPos(m_hwnd, NULL, x, y, 620, 505, SWP_NOZORDER | SWP_NOACTIVATE);
#else
      SetWindowPos(m_hwnd, NULL, x, y, 680, 505, SWP_NOZORDER | SWP_NOACTIVATE);
#endif

      WDL_FastString changelog;
      changelog.Set(g_module_path.Get());
      changelog.Append("changelog.txt");

      m_preview.SetParent(m_hwnd);
      m_preview.init(changelog.Get());
      m_preview.draw();
      m_preview.setCursor();

      SetTimer(m_hwnd, PREVIEW_EDITOR_TIMER, PREVIEW_EDITOR_TIMER_MS, NULL);

      SetFocus(cc);
    } break;
  case WM_TIMER:
    {
      if (wparam == PREVIEW_EDITOR_TIMER)
      {
        m_preview.RunEditor();
      }
    } break;
  case WM_DESTROY:
    {
      m_preview.ClearText();
      KillTimer(m_hwnd, PREVIEW_EDITOR_TIMER);

      RECT r;
      GetWindowRect(m_hwnd, &r);

      g_ini_file->write_int("changelog_wnd_x", r.left, EUTERPE_NAME);
      g_ini_file->write_int("changelog_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;
  case WM_SYSCOMMAND:
    {
      if (LOWORD(wparam) == SC_CLOSE)
      {
        DestroyWindow(m_hwnd);
      }
    } break;
  }

  return 0;
}
