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

#include "euterpe/pr_media_library_wnd.h"

#include <string.h>

#include "WDL/filebrowse.h"

RSE_MediaLibraryWnd::RSE_MediaLibraryWnd()
  : m_hwnd(NULL)
{}

RSE_MediaLibraryWnd::~RSE_MediaLibraryWnd()
{}

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

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

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

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

WDL_DLGRET RSE_MediaLibraryWnd::MediaLibraryWndProc(UINT msg, WPARAM wparam, LPARAM lparam)
{
  switch (msg)
  {
  case WM_INITDIALOG:
    {
      m_list = GetDlgItem(m_hwnd, IDC_LIST1);

      ListView_SetExtendedListViewStyleEx(m_list,
        LVS_EX_HEADERDRAGDROP | LVS_EX_FULLROWSELECT,
        LVS_EX_HEADERDRAGDROP | LVS_EX_FULLROWSELECT);

      ColumnHeader default_column_header[] =
      {
        {0, "Path", 355, LVCFMT_LEFT, 1, 0}
      };

      for (int i = 0; i < sizeof(default_column_header)/sizeof(default_column_header[0]); i++)
      {
        m_column_header.Add(default_column_header[i]);
      }

      LVCOLUMN lvc = { 0, };
      lvc.mask = LVCF_FMT | LVCF_TEXT | LVCF_WIDTH;

      int w = 0;
      WDL_FastString s;

      ColumnHeader *ch = m_column_header.Get();

      for (int i = 0; i < m_column_header.GetSize(); i++)
      {
        s.SetFormatted(128, "music_path_width_%02d", i);
        w = g_ini_file->read_int(s.Get(), ch[i].width, "preferences");
        lvc.cx = w;
        lvc.fmt = ch[i].fmt;
        lvc.pszText = (char *)ch[i].text;
        ListView_InsertColumn(m_list, i, &lvc);
      }

      WDL_TypedBuf<int> order_array;
      order_array.Resize(Header_GetItemCount(ListView_GetHeader(m_list)));
      int *oa = order_array.Get();

      for (int i = 0; i < order_array.GetSize(); i++)
      {
        s.SetFormatted(128, "music_path_order_%02d", i);
        oa[i] = g_ini_file->read_int(s.Get(), i, "preferences");
      }

      ListView_SetColumnOrderArray(m_list, order_array.GetSize(), order_array.Get());

      m_music_paths.Set(g_ini_file->read_str("music_paths", "", "preferences"));

      char *token = strtok(m_music_paths.Get(), ";");

      while (token != NULL)
      {
        int i = ListView_GetItemCount(m_list);

        LVITEM lvi = { 0, };
        lvi.mask = LVIF_TEXT | LVIF_PARAM;
        lvi.iItem = i;
        lvi.iSubItem = 0;
        lvi.lParam = i;
        lvi.pszText = token;
        lvi.cchTextMax = (int)strlen(token);

        ListView_InsertItem(m_list, &lvi);

        token = strtok(NULL, ";");
      }

      EnableWindow(GetDlgItem(m_hwnd, IDC_BUTTON2), FALSE);
    }
    break;
  case WM_DESTROY:
    {
      //if (g_storage_engine->IsOpen()) g_storage_engine->Close();

      WDL_FastString s;
      WDL_TypedBuf<int> order_array;

      order_array.Resize(Header_GetItemCount(ListView_GetHeader(m_list)));
      ListView_GetColumnOrderArray(m_list, order_array.GetSize(), order_array.Get());

      int *oa = order_array.Get();

      for (int i = 0; i < order_array.GetSize(); i++)
      {
        s.SetFormatted(128, "music_path_order_%02d", i);
        g_ini_file->write_int(s.Get(), oa[i], "preferences");
      }

      for (int i = 0; i < Header_GetItemCount(ListView_GetHeader(m_list)); i++)
      {
        s.SetFormatted(128, "music_path_width_%02d", i);
        g_ini_file->write_int(s.Get(), ListView_GetColumnWidth(m_list, i), "preferences");
      }

      m_column_header.Resize(0);

      m_hwnd = NULL;
    }
    break;
  case WM_NOTIFY:
    {
      switch (LOWORD(wparam))
      {
      case IDC_LIST1:
        {
          if (((LPNMHDR)lparam)->code == NM_CLICK)
          {
            m_selected_items.Resize(0);

            int pos = ListView_GetNextItem(m_list, -1, LVNI_SELECTED);

            while (pos != -1)
            {
              m_selected_items.Add(pos);
              pos = ListView_GetNextItem(m_list, pos, LVNI_SELECTED);
            }

            if (m_selected_items.GetSize())
            {
              EnableWindow(GetDlgItem(m_hwnd, IDC_BUTTON2), TRUE);
            }
            else
            {
              EnableWindow(GetDlgItem(m_hwnd, IDC_BUTTON2), FALSE);
            }
          }
        }
        break;
      }
    }
    break;
  case WM_COMMAND:
    {
      switch (LOWORD(wparam))
      {
      case IDC_BUTTON1:
        {
          char path[2048] = { 0 };

          if (WDL_ChooseDirectory(m_hwnd, "Select music path", NULL, path, sizeof(path), true))
          {
            LVITEM lvi = { 0, };

            WDL_String strbuf;
            int item_count = ListView_GetItemCount(m_list);
            ColumnHeader *ch = m_column_header.Get();
            for (int i = 0; i < m_column_header.GetSize(); i++)
            {
              lvi.mask = LVIF_TEXT;
              lvi.iItem = item_count;
              lvi.iSubItem = i;
              switch (ch[i].id)
              {
              case 0:
                lvi.mask = LVIF_TEXT | LVIF_PARAM;
                lvi.lParam = (LPARAM)item_count;
                lvi.pszText = path;
                lvi.cchTextMax = (int)strlen(path);
                ListView_InsertItem(m_list, &lvi);
                break;
              }
              WDL_UTF8_HookListView(m_list);
            }

            m_music_paths.Set("");

            for (int i = 0; i < ListView_GetItemCount(m_list); i++)
            {
              ListView_GetItemText(m_list, i, 0, path, sizeof(path));
              m_music_paths.Append(path);
              m_music_paths.Append(";");
            }

            g_ini_file->write_str("music_paths", m_music_paths.Get(), "preferences");
          }
        }
        break;
      case IDC_BUTTON2:
        {
          while (m_selected_items.GetSize())
          {
            int *x = m_selected_items.Get();
            int i = m_selected_items.GetSize() - 1;
            ListView_DeleteItem(m_list, x[i]);
            m_selected_items.Delete(i);
          }

          char path[2048] = { 0 };
          m_music_paths.Set("");

          for (int i = 0; i < ListView_GetItemCount(m_list); i++)
          {
            ListView_GetItemText(m_list, i, 0, path, sizeof(path));
            m_music_paths.Append(path);
            m_music_paths.Append(";");
          }

          g_ini_file->write_str("music_paths", m_music_paths.Get(), "preferences");

          EnableWindow(GetDlgItem(m_hwnd, IDC_BUTTON2), FALSE);
        }
        break;
      }
    }
    break;
  }

  return 0;
}
