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

#include "euterpe/file_prog_wnd.h"
#include "euterpe/app_info.h"
#include "euterpe/main_wnd.h"
#include "euterpe/file_tasks.h"

#define RSE_FILE_TASKS_PROGRESS 1200
#define RSE_FILE_TASKS_PROGRESS_MS 50

RSE_FileTasksProgressWnd::RSE_FileTasksProgressWnd()
  : m_hwnd(NULL)
  , m_per(0)
{}

RSE_FileTasksProgressWnd::~RSE_FileTasksProgressWnd()
{}

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

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

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

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

WDL_DLGRET RSE_FileTasksProgressWnd::FileTasksProgressWndProc(UINT msg, WPARAM wparam, LPARAM lparam)
{
  switch (msg)
  {
  case WM_INITDIALOG:
    {
      int x, y;
      x = g_ini_file->read_int("file_prog_wnd_x", 0, EUTERPE_NAME);
      y = g_ini_file->read_int("file_prog_wnd_y", 50, EUTERPE_NAME);
      SetWindowPos(m_hwnd, NULL, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);

      SetTimer(m_hwnd, RSE_FILE_TASKS_PROGRESS, RSE_FILE_TASKS_PROGRESS_MS, NULL);
    }
    break;
  case WM_DESTROY:
    {
      RECT r;
      GetWindowRect(m_hwnd, &r);
      g_ini_file->write_int("file_prog_wnd_x", r.left, EUTERPE_NAME);
      g_ini_file->write_int("file_prog_wnd_y", r.top, EUTERPE_NAME);

      KillTimer(m_hwnd, RSE_FILE_TASKS_PROGRESS);

      m_per = 0;
      m_hwnd = NULL;
    }
    break;
  case WM_TIMER:
    {
      if (wparam == RSE_FILE_TASKS_PROGRESS)
      {
        RSE_FileTasks *ft = g_main_wnd->FileTask();
        int idx = ft->CurrentIndex() + 1;
        int tot = ft->TotalFiles();
        int per = (tot > 0) ? (idx * 100) / tot : 0;

        if (m_per < per) m_per = per;

        SetWindowText(GetDlgItem(m_hwnd, IDC_STATIC1), ft->FileInProgress());
        SendMessage(GetDlgItem(m_hwnd, IDC_PROGRESS1), PBM_SETRANGE, 0, MAKELPARAM(0, 100));

        if (m_per)
        {
          SendMessage(GetDlgItem(m_hwnd, IDC_PROGRESS1), PBM_SETPOS, m_per, 0);
        }
      }
    }
    break;
  case WM_COMMAND:
    {
      switch(LOWORD(wparam))
      {
      case IDCANCEL:
        {
          g_main_wnd->FileTask()->AbortOperation();
        }
        break;
      }
    }
  }

  return 0;
}
