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

#ifndef _RSI_QUERY_H_
#define _RSI_QUERY_H_

#include "RSI/definitions.h"
#include "third_party/sqlite/sqlite3.h"

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

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

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

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

  bool HasRow() const;
  const char *GetColumnText(int col);
  double GetColumnDouble(int col);
  WDL_INT64 GetColumnInt64(int col);
  void NextStep();
private:
  static unsigned WINAPI ThreadFunc(void *arg);
  int Run();

  HANDLE m_thread;
  bool m_killthread;
  mutable 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_querytext;
};

#endif // _RSI_QUERY_H_
