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

#ifndef _THA_QUERY_H_
#define _THA_QUERY_H_

#include "thalia/definitions.h"
#include "thalia/playlist.h"
#include "third_party/sqlite/sqlite3.h"

#include "WDL/assocarray.h"
#include "WDL/wdlstring.h"
#include "WDL/ptrlist.h"
#include "WDL/mutex.h"

class THA_Query
{
public:
  THA_Query();
  ~THA_Query();

  bool Open();
  bool IsOpen() const;
  void Close();

  bool Query();
  bool Query(const char *text);
  bool Order(const char *col, bool asc);
  const char *QueryText();

  struct TitlePath
  {
    WDL_FastString title;
    WDL_FastString path;
  };

  typedef WDL_PtrList<TitlePath> Title;
  typedef WDL_StringKeyedArray<Title *> Album;
  typedef WDL_StringKeyedArray<Album *> Artist;

  bool WantArtists();
  void DoneWithArtists();
  THA_Query::Artist *GetArtists();

  void GetPlayListEntry(const char *filepath,
    WDL_PtrList<THA_PlayList::PlayListEntry> *entry);
  void GetUserPlayListEntry(const char *filepath,
    WDL_PtrList<THA_PlayList::PlayListEntry> *entry);

  bool QueryForPlayList(const char *text);
  bool WantMatches();
  void DoneWithMatches();
  WDL_PtrList<WDL_FastString> *GetMatches();
private:
  static unsigned WINAPI ThreadFunc(void *arg);
  int Run();

  static int titlecmp(const TitlePath *a, const TitlePath *b)
  {
    return stricmp(a->title.Get(), b->title.Get());
  }

  bool HasRow();
  const char *GetColumnText(int col);
  double GetColumnDouble(int col);
  WDL_INT64 GetColumnInt64(int col);
  void NextStep();
  void LoadArtists();
  void DeleteAllArtists();
  void LoadPlayListMatches();

  HANDLE m_thread;
  bool m_killthread;
  WDL_Mutex m_mutex;
  int m_action;

  bool m_open;
  WDL_FastString m_fn;
  sqlite3 *m_db;
  sqlite3_stmt *m_stmt;
  char *m_errmsg;

  WDL_FastString m_strbuf;

  int m_step;
  int m_querylimit;
  WDL_FastString m_querysql;
  WDL_FastString m_querytext;

  THA_Query::Artist *m_artists;
  bool m_wantartists;

  WDL_PtrList<WDL_FastString> *m_matches;
  bool m_wantmatches;
};

#endif // _THA_QUERY_H_
