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

#include "RSI/load_wnd.h"

#define RSI_FILE_LOAD_PROGRESS 320
#define RSI_FILE_LOAD_PROGRESS_MS 50

static HWND m_hwnd = NULL;
static UINT m_msg;
static WPARAM m_wparam;
static LPARAM m_lparam;
static int m_x, m_y;
static WDL_WndSizer m_resize;
static WDL_FastString m_xstr, m_ystr, m_wstr, m_hstr;

static void LoadWnd_InitDialog()
{
  g_loadwnd = m_hwnd;
  m_x = GetPrivateProfileInt(RSI_NAME, "load_wnd_x", 50, g_inipath.Get());
  m_y = GetPrivateProfileInt(RSI_NAME, "load_wnd_y", 50, g_inipath.Get());
  SetWindowPos(m_hwnd, NULL, m_x, m_y, 0, 0, SWP_NOSIZE | SWP_NOACTIVATE);

  ShowWindow(m_hwnd, SW_SHOW);
  SetTimer(m_hwnd, RSI_FILE_LOAD_PROGRESS, RSI_FILE_LOAD_PROGRESS_MS, NULL);
}

static void LoadWnd_Destroy()
{
  KillTimer(m_hwnd, RSI_FILE_LOAD_PROGRESS);

  WritePrivateProfileString(RSI_NAME, "load_wnd_x", m_xstr.Get(), g_inipath.Get());
  WritePrivateProfileString(RSI_NAME, "load_wnd_y", m_ystr.Get(), g_inipath.Get());
  //WritePrivateProfileString(RSI_NAME, "load_wnd_w", m_wstr.Get(), g_inipath.Get());
  //WritePrivateProfileString(RSI_NAME, "load_wnd_h", m_hstr.Get(), g_inipath.Get());

  g_loadwnd = NULL;
}

static void LoadWnd_Move()
{
  RECT r;
  GetWindowRect(m_hwnd, &r);

  m_xstr.SetFormatted(32, "%d", r.left);
  m_ystr.SetFormatted(32, "%d", r.top);
  //m_wstr.SetFormatted(32, "%d", r.right - r.left);
  //m_hstr.SetFormatted(32, "%d", r.bottom - r.top);
}

static void LoadWnd_Timer()
{
  if (m_wparam == RSI_FILE_LOAD_PROGRESS)
  {
    SendMessage(GetDlgItem(m_hwnd, IDC_PROGRESS1), PBM_SETRANGE, 0, MAKELPARAM(0, 100));

    if (g_rendersystem->IsLoadingInProgress())
    {
      int perc = g_rendersystem->LoadingProgress();
      SendMessage(GetDlgItem(m_hwnd, IDC_PROGRESS1), PBM_SETPOS, perc, 0);
    }
    else
    {
      EndDialog(m_hwnd, 0);
    }
  }
}

static void LoadWnd_SysCommand()
{
  if (m_wparam == SC_CLOSE)
  {
    if (g_rendersystem->IsLoadingInProgress()) g_rendersystem->AbortLoading();
    if (g_loadwnd) { EndDialog(m_hwnd, 0); }
  }
}

static void LoadWnd_Command()
{
  switch(LOWORD(m_wparam))
  {
  case IDC_BUTTON1:
  case IDCANCEL:
    {
      if (g_rendersystem->IsLoadingInProgress()) g_rendersystem->AbortLoading();
      if (g_loadwnd) { EndDialog(m_hwnd, 0); }
    }
    break;
  }
}

WDL_DLGRET RSI_LoadWndProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
{
  m_hwnd = hwnd;
  m_msg = msg;
  m_wparam = wparam;
  m_lparam = lparam;

  switch(msg)
  {
    case WM_INITDIALOG: LoadWnd_InitDialog(); break;
    //case WM_SYSCOMMAND: LoadWnd_SysCommand(); break;
    //case WM_CLOSE: return 0; break;
    case WM_MOVE: LoadWnd_Move(); break;
    case WM_DESTROY: LoadWnd_Destroy(); break;
    case WM_COMMAND: LoadWnd_Command(); break;
    case WM_TIMER: LoadWnd_Timer(); break;
  }

  return 0;
}
