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

#include "RSI/preferences.h"
#include "RSI/definitions.h"
#include "RSI/rsi_plugin.h"
#include "RSI/app_info.h"
#include "RSI/main_wnd.h"
#include "third_party/libebur128/ebur128/ebur128.h"

#include "WDL/fileread.h"
#include "WDL/filewrite.h"

static const char *default_preferences[] =
{
  "//",
  "// Welcome to " RSI_NAME_MARKETING " " RSI_ARCH " Audio System, Version " RSI_NAKED_VERSION,
  "//",
  "// RSI preferences",
  "//",
  "",
  "{",
  "  // Display preferences with Curses interface",
  "  // (supports only ASCII for text input).",
  "  // If set to false it uses an external editor.",
  "  \"curses_preferences\": true,",
  "  \"curses_right_focus\": true,",
  "",
  "  // Set the audio system (if available).",
#if defined(_WIN32)
  "  // 0: WaveOut (legacy)",
  "  // 1: DirectSound",
  "  // 2: WASAPI (Windows Vista/7/8/10)",
  "  \"audio_system\": 0,",
#elif defined(__linux__)
  "  // 0: PulseAudio",
  "  \"audio_system\": 0,",
#endif
  "",
  "  // Set the samplerate for the audio device (if available).",
  "  // Most common values (Hz): 8000, 11025, 16000,",
  "  // 22050, 32000, 44100 (default), 48000, 88200,",
  "  // 96000, 176400, 192000.",
  "  \"audio_device_samplerate\": 44100,",
  "",
  "  // Set the bit depth for the audio device (if available).",
  "  // 0: 16-bit, 1: 24-bit, 2: 32-bit, 3: 32-bit FP.",
  "  \"audio_device_bit_depth\": 0,",
#if 0
  "",
  "  // Set the output channels for the audio device (if available).",
  "  // Currently available options are 2 and 4, the later if you",
  "  // want to route audio to a secondary output such as headphones.",
  "  \"audio_device_output_channels\": 2,",
#endif
#if 0 //defined(_WIN32)
  "",
  "  // Set WASAPI exclusive mode (advanced).",
  "  // When is set to false it overrides \"audio_device_samplerate\"",
  "  // and \"audio_device_bit_depth\" and opens the device in",
  "  // shared mode with the settings in Windows preferences",
  "  // related to: Audio Device Default Format.",
  "  \"wasapi_exclusive_mode\": false,",
#elif defined(__linux__)

#endif
  "",
  "  // Set media buffer size (ms) for each track.",
  "  // Memory consumption for one (1) media buffer",
  "  // can be calculated with the following formula:",
  "  //",
  "  //   sizeof(double) * audio_device_samplerate * (ms / 1000)",
  "  //     * 2 = bytes",
  "  //       |",
  "  //       + channels (stereo)",
  "  //",
  "  // Effective pipeline bitrate for one (1) media buffer",
  "  // can be calculated with the following formula:",
  "  //",
  "  //   sizeof(double) * audio_device_samplerate",
  "  //     * 2 * 8 = bit/sec",
  "  //       |   |",
  "  //       |   + computer memory unit (bit)",
  "  //       + channels (stereo)",
  "  //",
  "  // Not to be confused with the actual memory footprint",
  "  // of RSI but rather as its minimum contribution to it.",
  "  \"media_buffer_size\": 200,",
  "",
  "  // Disk read mode.",
  "  // 1: Asynchronous unbuffered",
  "  // 2: Asynchronous buffered",
  "  // -1: Synchronous unbuffered",
  "  \"disk_read_mode\": 2,",
  "  \"read_buffer_size\": 262144,",
  "  \"read_buffers\": 3,",
  "",
  "  // Disk write mode.",
  "  // 1: Asynchronous buffered",
  "  // 2: Asynchronous write-through",
  "  // 3: Asynchronous unbuffered",
  "  // 0: Synchronous",
  "  \"disk_write_mode\": 1,",
  "  \"write_buffer_size\": 65536,",
  "  \"write_buffers_min\": 16,",
  "  \"write_buffers_max\": 128,",
  "",
  "  // Disk I/O thread priority.",
  "  // - \"idle\"",
  "  // - \"below_normal\"",
  "  // - \"normal\"",
  "  // - \"above_normal\"",
  "  // - \"highest\"",
  "  // - \"time_critical\"",
  "  \"disk_io_priority\": \"normal\",",
  "  \"disk_io_sleepstep\": 20,",
  "",
  "  // Resample mode.",
  "  // 0: Linear interpolation",
  "  // 1: 16pt sinc",
  "  // 2: 64pt sinc",
  "  // 3: 192pt sinc",
  "  // 4: 384pt sinc",
  "  // 5: 512pt sinc",
  "  // 6: 768pt sinc",
  "  \"resample_mode\": 2,",
  "",
  "  // Render system thread priority.",
  "  // - \"idle\"",
  "  // - \"below_normal\"",
  "  // - \"normal\"",
  "  // - \"above_normal\"",
  "  // - \"highest\"",
  "  // - \"time_critical\"",
  "  \"render_system_priority\": \"normal\",",
  "  \"render_system_sleepstep\": 20,",
  "",
  "  // Pitch shift and time stretch steps.",
  "  \"shift_step\": 0.1,",
  "  \"tempo_step\": 0.1,",
  "  \"shift_altstep\": 0.01,",
  "  \"tempo_altstep\": 0.01,",
  "",
  "  // Eject track when is drained.",
  "  \"auto_eject_track\": false,",
  "",
  "  // Default value for track repeat.",
  "  \"track_repeat\": false,",
  "",
  "  // Set value for volume dB step (increase/decrease).",
  "  \"volume_step\": 2.0,",
  "",
  "  // If playback is active RSI asks if you really want to exit.",
  "  \"ask_exit\": false,",
  "",
  "  // EBU R128 standard for loudness normalization.",
  "  // Loudness reference.",
  "  //   0: -23 LUFS (standard)",
  "  //   1: -18 LUFS (RG2 - backwards compatible with RG1)",
  "  //   2: -16 LUFS",
  "  //   3: -14 LUFS",
  "  //   4: -11 LUFS",
  "  // Loudness mode.",
  "  //   0: M (momentary)",
  "  //   1: S (shortterm)",
  "  //   2: I (integrated)",
  "  //   3: LRA (range)",
  "  //   4: sample peak",
  "  //   5: true peak",
  "  \"ebur128_normalization\": false,",
  "  \"ebur128_downward_only\": true,",
  "  \"ebur128_reference\": 0,",
  "  \"ebur128_mode\": 2,",
  "",
  "  // File dialog.",
  "  \"preserve_current_directory\": true,",
  //"",
  //"  // Presentation.",
  //"  // Colors in hexadecimal format (hex triplet).",
  //"  \"background_color\": \"000000\",",
  //"  \"text_color\": \"C0C0C0\",",
  //"",
  //"  // Dialog font size (8-72).",
  //"  \"main_dialog_font_size\": 20,",
  //"  \"stats_dialog_font_size\": 20,",
  "",
  "  // Media library paths.",
  "  // An array of strings which are valid paths",
  "  // e.g. \"media_library_paths\": [\"D:\\\\music_a\", \"D:\\\\music_b\"]",
  "  //      Note that escape character is needed for windows paths",
  "  \"media_library_paths\": [],",
  "",
  "  // Media library query.",
  "  // Limit media library query to N rows",
  "  \"media_library_query_limit\": 300,",
  "",
  "  // Antidote bit depth for in-memory storage.",
  "  // Storage bit depth.",
  "  //   0: 16-bit, 1: 24-bit, 2: 32-bit, 3: 32-bit FP, 4: 64-bit FP.",
  "  // Memory pre-allocation (in seconds per slot).",
  "  //   0.0: disables pre-allocation",
  "  // Memory consumption for one (1) data bank slot",
  "  // can be calculated with the following formula:",
  "  //",
  "  //   sizeof(bit-depth) * audio_device_samplerate * seconds",
  "  //     * 2 = bytes",
  "  //       |",
  "  //       + channels (stereo)",
  "  //",
  "  \"antidote_bit_depth\": 0,",
  "  \"antidote_pre_allocate\": 0.0",
  "}",
};

RSI_Preferences::RSI_Preferences()
  : m_pf(NULL)
  , m_relaunch(false)
{}

RSI_Preferences::~RSI_Preferences()
{
  cJSON_Delete(m_pf);
}

void RSI_Preferences::Create()
{
  WDL_FastString defpref, usrpref;

  for (int i = 0; i < (int)sizeof(default_preferences) / (int)sizeof(default_preferences[0]); i++)
  {
    defpref.AppendFormatted(2048, "%s\n", default_preferences[i]);
  }

  const char *user_preferences[] =
  {
    "{",
    "  // Add your personal preferences here.",
    "  // Your changes will take effect the next time you relaunch RSI.",
    "}"
  };

  for (int j = 0; j < (int)sizeof(user_preferences) / (int)sizeof(user_preferences[0]); j++)
  {
    usrpref.AppendFormatted(2048, "%s\n", user_preferences[j]);
  }

  WDL_FastString def(g_setpath), usr(g_setpath);
  def.Append("preferences-default.txt");
  usr.Append("preferences.txt");

  // Create default preferences file
  WDL_FileWrite *cdf = new WDL_FileWrite(def.Get());
  if (cdf && cdf->IsOpen())
  {
    cdf->Write(defpref.Get(), defpref.GetLength());
  }

  if (cdf) { delete cdf; cdf = NULL; }

  // Check if user preferences exist
  WDL_FileRead *uf = new WDL_FileRead(usr.Get());
  if (uf && !uf->IsOpen())
  {
    // Create user preferences file
    WDL_FileWrite *cuf = new WDL_FileWrite(usr.Get());
    if (cuf && cuf->IsOpen())
    {
      cuf->Write(usrpref.Get(), usrpref.GetLength());
    }

    if (cuf) { delete cuf; cuf = NULL; }
  }

  if (uf) { delete uf; uf = NULL; }
}

void RSI_Preferences::Open(bool default_file)
{
  WDL_FastString def(g_setpath), usr(g_setpath);
  def.Append("preferences-default.txt");
  usr.Append("preferences.txt");

  ShellExecute(g_mainwnd->Handle(), "", "notepad.exe", default_file ? def.Get() : usr.Get(), "", SW_SHOWNORMAL);
}

bool RSI_Preferences::Parse(bool default_file)
{
  WDL_FastString def(g_setpath), usr(g_setpath);
  def.Append("preferences-default.txt");
  usr.Append("preferences.txt");

  WDL_FileRead fr(default_file ? def.Get() : usr.Get());
  WDL_TypedBuf<char> strbuf;
  strbuf.Resize((int)fr.GetSize());
  fr.Read(strbuf.Get(), strbuf.GetSize());
  strbuf.Add('\0');

  cJSON_Minify(strbuf.Get());
  m_pf = cJSON_Parse(strbuf.Get());

  if (!m_pf)
  {
    const char *error_ptr = cJSON_GetErrorPtr();
    if (error_ptr)
    {
      m_err.SetFormatted(2048, "Parse error before: %s\n", error_ptr);
      wdl_log(m_err.Get());
    }

    return false;
  }

  return true;
}

bool RSI_Preferences::WantCurses() const
{
  const cJSON *curses = NULL;
  curses = cJSON_GetObjectItemCaseSensitive(m_pf, "curses_preferences");
  if (cJSON_IsTrue(curses)) return true;
  else if (cJSON_IsFalse(curses)) return false;
  else return true;
}

bool RSI_Preferences::WantCursesRightFocus() const
{
  const cJSON *curses_right_focus = NULL;
  curses_right_focus = cJSON_GetObjectItemCaseSensitive(m_pf, "curses_right_focus");
  if (cJSON_IsTrue(curses_right_focus)) return true;
  else if (cJSON_IsFalse(curses_right_focus)) return false;
  else return true;
}

int RSI_Preferences::GetAudioSystem() const
{
  const cJSON *audio_system = NULL;
  audio_system = cJSON_GetObjectItemCaseSensitive(m_pf, "audio_system");
  if (cJSON_IsNumber(audio_system))
  {
#if defined(_WIN32)
    // 0: WaveOut, 1: DirectSound, 2: WASAPI.
    if (audio_system->valueint >= 0 && audio_system->valueint <= 2)
#elif defined(__linux__)
    // 0: PulseAudio.
    if (audio_system->valueint == 0)
#endif
    {
      return audio_system->valueint;
    }
    else return 0;
  }
  else return 0;
}

double RSI_Preferences::GetAudioDeviceSamplerate() const
{
  if (!GetWASAPIExclusiveMode())
  {
    if (g_audiostreamer) return g_audiostreamer->GetSampleRate();
  }

  const cJSON *dev_srate = NULL;
  dev_srate = cJSON_GetObjectItemCaseSensitive(m_pf, "audio_device_samplerate");
  if (cJSON_IsNumber(dev_srate))
  {
    if (dev_srate->valueint == 8000 || dev_srate->valueint == 11025 ||
      dev_srate->valueint == 16000 || dev_srate->valueint == 22050 ||
      dev_srate->valueint == 32000 || dev_srate->valueint == 44100 ||
      dev_srate->valueint == 48000 || dev_srate->valueint == 88200 ||
      dev_srate->valueint == 96000 || dev_srate->valueint == 176400 ||
      dev_srate->valueint == 192000)
    {
      return dev_srate->valuedouble;
    }
    else return 44100.0;
  }
  else return 44100.0;
}

int RSI_Preferences::GetAudioDeviceBitDepth() const
{
  const cJSON *dev_bit_depth = NULL;
  dev_bit_depth = cJSON_GetObjectItemCaseSensitive(m_pf, "audio_device_bit_depth");
  if (cJSON_IsNumber(dev_bit_depth))
  {
    // 0: 16-bit, 1: 24-bit, 2: 32-bit, 3: 32-bit FP.
    if (dev_bit_depth->valueint >= 0 && dev_bit_depth->valueint <= 3)
    {
      return dev_bit_depth->valueint;
    }
    else return 0;
  }
  else return 0;
}

int RSI_Preferences::GetAudioDeviceOutputChannels() const
{
  //const cJSON *nch = NULL;
  //nch = cJSON_GetObjectItemCaseSensitive(m_pf, "audio_device_output_channels");
  //if (cJSON_IsNumber(nch))
  //{
  //  if (nch->valueint == 2 || nch->valueint == 4) return nch->valueint;
  //  else return 2;
  //}
  //else return 2;
  return 2;
}

int RSI_Preferences::GetMediaBufferSize() const
{
  const cJSON *mbs = NULL;
  mbs = cJSON_GetObjectItemCaseSensitive(m_pf, "media_buffer_size");
  if (cJSON_IsNumber(mbs))
  {
    if (mbs->valueint > 0) return mbs->valueint;
    else return 200;
  }
  else return 200;
}

void RSI_Preferences::GetDiskReadMode(int *rmode, int *rbufsize, int *rnbufs) const
{
  const cJSON *disk_read_mode = NULL;
  const cJSON *read_buffer_size = NULL;
  const cJSON *read_buffers = NULL;
  disk_read_mode = cJSON_GetObjectItemCaseSensitive(m_pf, "disk_read_mode");
  if (cJSON_IsNumber(disk_read_mode))
  {
    if (disk_read_mode->valueint >= -1 && disk_read_mode->valueint <= 2)
    {
      *rmode = disk_read_mode->valueint;
    }
    else *rmode = 2;
  }
  else *rmode = 2;

  read_buffer_size = cJSON_GetObjectItemCaseSensitive(m_pf, "read_buffer_size");
  if (cJSON_IsNumber(read_buffer_size))
  {
    if (read_buffer_size->valueint > 0)
    {
      *rbufsize = read_buffer_size->valueint;
    }
    else *rbufsize = 262144;
  }
  else *rbufsize = 262144;

  read_buffers = cJSON_GetObjectItemCaseSensitive(m_pf, "read_buffers");
  if (cJSON_IsNumber(read_buffers))
  {
    if (read_buffers->valueint > 0)
    {
      *rnbufs = read_buffers->valueint;
    }
    else *rnbufs = 3;
  }
  else *rnbufs = 3;
}

void RSI_Preferences::GetDiskWriteMode(int *wmode, int *wbufsize, int *wminbufs, int *wmaxbufs) const
{
  const cJSON *disk_write_mode = NULL;
  const cJSON *write_buffer_size = NULL;
  const cJSON *write_buffers_min = NULL;
  const cJSON *write_buffers_max = NULL;
  disk_write_mode = cJSON_GetObjectItemCaseSensitive(m_pf, "disk_write_mode");
  if (cJSON_IsNumber(disk_write_mode))
  {
    if (disk_write_mode->valueint >= 0 && disk_write_mode->valueint <= 3)
    {
      *wmode = disk_write_mode->valueint;
    }
    else *wmode = 1;
  }
  else *wmode = 1;

  write_buffer_size = cJSON_GetObjectItemCaseSensitive(m_pf, "write_buffer_size");
  if (cJSON_IsNumber(write_buffer_size))
  {
    if (write_buffer_size->valueint > 0)
    {
      *wbufsize = write_buffer_size->valueint;
    }
    else *wbufsize = 65536;
  }
  else *wbufsize = 65536;

  write_buffers_min = cJSON_GetObjectItemCaseSensitive(m_pf, "write_buffers_min");
  if (cJSON_IsNumber(write_buffers_min))
  {
    if (write_buffers_min->valueint > 0)
    {
      *wminbufs = write_buffers_min->valueint;
    }
    else *wminbufs = 16;
  }
  else *wminbufs = 16;

  write_buffers_max = cJSON_GetObjectItemCaseSensitive(m_pf, "write_buffers_max");
  if (cJSON_IsNumber(write_buffers_max))
  {
    if (write_buffers_max->valueint > 0)
    {
      *wmaxbufs = write_buffers_max->valueint;
    }
    else *wmaxbufs = 128;
  }
  else *wmaxbufs = 128;

  if (*wminbufs > *wmaxbufs) *wminbufs = *wmaxbufs;
}

int RSI_Preferences::GetDiskIOPriority() const
{
  const cJSON *disk_io_priority = NULL;
  disk_io_priority = cJSON_GetObjectItemCaseSensitive(m_pf, "disk_io_priority");
  if (cJSON_IsString(disk_io_priority) && (disk_io_priority->valuestring != NULL))
  {
    if (!strcmp(disk_io_priority->valuestring, "idle"))
    {
      return THREAD_PRIORITY_IDLE;
    }
    else if (!strcmp(disk_io_priority->valuestring, "below_normal"))
    {
      return THREAD_PRIORITY_BELOW_NORMAL;
    }
    else if (!strcmp(disk_io_priority->valuestring, "normal"))
    {
      return THREAD_PRIORITY_NORMAL;
    }
    else if (!strcmp(disk_io_priority->valuestring, "above_normal"))
    {
      return THREAD_PRIORITY_ABOVE_NORMAL;
    }
    else if (!strcmp(disk_io_priority->valuestring, "highest"))
    {
      return THREAD_PRIORITY_HIGHEST;
    }
    else if (!strcmp(disk_io_priority->valuestring, "time_critical"))
    {
      return THREAD_PRIORITY_TIME_CRITICAL;
    }
    else return THREAD_PRIORITY_NORMAL;
  }
  else return THREAD_PRIORITY_NORMAL;
}

int RSI_Preferences::GetDiskIOSleepStep() const
{
  const cJSON *disk_io_sleepstep = NULL;
  disk_io_sleepstep = cJSON_GetObjectItemCaseSensitive(m_pf, "disk_io_sleepstep");
  if (cJSON_IsNumber(disk_io_sleepstep))
  {
    if (disk_io_sleepstep->valueint >= 0) return disk_io_sleepstep->valueint;
    else return 20;
  }
  else return 20;
}

int RSI_Preferences::GetAntidoteBitDepth() const
{
  const cJSON *antidote_bit_depth = NULL;
  antidote_bit_depth = cJSON_GetObjectItemCaseSensitive(m_pf, "antidote_bit_depth");
  if (cJSON_IsNumber(antidote_bit_depth))
  {
    // 0: 16-bit, 1: 24-bit, 2: 32-bit, 3: 32-bit FP, 4: 64-bit FP.
    if (antidote_bit_depth->valueint >= 0 && antidote_bit_depth->valueint <= 4)
    {
      return antidote_bit_depth->valueint;
    }
    else return 0;
  }
  else return 0;
}

double RSI_Preferences::GetAntidotePreAllocate() const
{
  const cJSON *antidote_pre_allocate = NULL;
  antidote_pre_allocate = cJSON_GetObjectItemCaseSensitive(m_pf, "antidote_pre_allocate");
  if (cJSON_IsNumber(antidote_pre_allocate))
  {
    if (antidote_pre_allocate->valueint >= 0)
    {
      return antidote_pre_allocate->valuedouble;
    }
    else return 0.0;
  }
  else return 0.0;
}

void RSI_Preferences::GetResampleMode(bool *interp, int *filtercnt, bool *sinc,
  int *sinc_size, int *sinc_interpsize) const
{
  const cJSON *resample_mode = NULL;
  resample_mode = cJSON_GetObjectItemCaseSensitive(m_pf, "resample_mode");
  if (cJSON_IsNumber(resample_mode))
  {
    if (resample_mode->valueint >= 0 && resample_mode->valueint <= 6)
    {
      switch (resample_mode->valueint)
      {
      case 0:
        *interp = true; *filtercnt = 1;
        *sinc = false; *sinc_size = 64; *sinc_interpsize = 32;
        break;
      case 1:
        *interp = true; *filtercnt = 1;
        *sinc = true; *sinc_size = 16; *sinc_interpsize = 8;
        break;
      case 2:
        *interp = true; *filtercnt = 1;
        *sinc = true; *sinc_size = 64; *sinc_interpsize = 32;
        break;
      case 3:
        *interp = true; *filtercnt = 1;
        *sinc = true; *sinc_size = 192; *sinc_interpsize = 96;
        break;
      case 4:
        *interp = true; *filtercnt = 1;
        *sinc = true; *sinc_size = 384; *sinc_interpsize = 192;
        break;
      case 5:
        *interp = true; *filtercnt = 1;
        *sinc = true; *sinc_size = 512; *sinc_interpsize = 256;
        break;
      case 6:
        *interp = true; *filtercnt = 1;
        *sinc = true; *sinc_size = 768; *sinc_interpsize = 384;
        break;
      }
    }
    else
    {
      *interp = true; *filtercnt = 1;
      *sinc = true; *sinc_size = 64; *sinc_interpsize = 32;
    }
  }
  else
  {
    *interp = true; *filtercnt = 1;
    *sinc = true; *sinc_size = 64; *sinc_interpsize = 32;
  }
}

int RSI_Preferences::GetRenderSystemPriority() const
{
  const cJSON *render_system_priority = NULL;
  render_system_priority = cJSON_GetObjectItemCaseSensitive(m_pf, "render_system_priority");
  if (cJSON_IsString(render_system_priority) && (render_system_priority->valuestring != NULL))
  {
    if (!strcmp(render_system_priority->valuestring, "idle"))
    {
      return THREAD_PRIORITY_IDLE;
    }
    else if (!strcmp(render_system_priority->valuestring, "below_normal"))
    {
      return THREAD_PRIORITY_BELOW_NORMAL;
    }
    else if (!strcmp(render_system_priority->valuestring, "normal"))
    {
      return THREAD_PRIORITY_NORMAL;
    }
    else if (!strcmp(render_system_priority->valuestring, "above_normal"))
    {
      return THREAD_PRIORITY_ABOVE_NORMAL;
    }
    else if (!strcmp(render_system_priority->valuestring, "highest"))
    {
      return THREAD_PRIORITY_HIGHEST;
    }
    else if (!strcmp(render_system_priority->valuestring, "time_critical"))
    {
      return THREAD_PRIORITY_TIME_CRITICAL;
    }
    else return THREAD_PRIORITY_NORMAL;
  }
  else return THREAD_PRIORITY_NORMAL;
}

int RSI_Preferences::GetRenderSystemSleepStep() const
{
  const cJSON *render_system_sleepstep = NULL;
  render_system_sleepstep = cJSON_GetObjectItemCaseSensitive(m_pf, "render_system_sleepstep");
  if (cJSON_IsNumber(render_system_sleepstep))
  {
    if (render_system_sleepstep->valueint >= 0) return render_system_sleepstep->valueint;
    else return 20;
  }
  else return 20;
}

bool RSI_Preferences::GetWASAPIExclusiveMode() const
{
  //const cJSON *wasapi_exclusive_mode = NULL;
  //wasapi_exclusive_mode = cJSON_GetObjectItemCaseSensitive(m_pf, "wasapi_exclusive_mode");
  //if (cJSON_IsTrue(wasapi_exclusive_mode)) return true;
  //else if (cJSON_IsFalse(wasapi_exclusive_mode)) return false;
  //else return false;
  return true;
}

double RSI_Preferences::GetShiftStep() const
{
  const cJSON *shift_step = NULL;
  shift_step = cJSON_GetObjectItemCaseSensitive(m_pf, "shift_step");
  if (cJSON_IsNumber(shift_step))
  {
    return shift_step->valuedouble;
  }
  else return 0.1;
}

double RSI_Preferences::GetTempoStep() const
{
  const cJSON *tempo_step = NULL;
  tempo_step = cJSON_GetObjectItemCaseSensitive(m_pf, "tempo_step");
  if (cJSON_IsNumber(tempo_step))
  {
    return tempo_step->valuedouble;
  }
  else return 0.1;
}

double RSI_Preferences::GetShiftAltStep() const
{
  const cJSON *shift_altstep = NULL;
  shift_altstep = cJSON_GetObjectItemCaseSensitive(m_pf, "shift_altstep");
  if (cJSON_IsNumber(shift_altstep))
  {
    return shift_altstep->valuedouble;
  }
  else return 0.01;
}

double RSI_Preferences::GetTempoAltStep() const
{
  const cJSON *tempo_altstep = NULL;
  tempo_altstep = cJSON_GetObjectItemCaseSensitive(m_pf, "tempo_altstep");
  if (cJSON_IsNumber(tempo_altstep))
  {
    return tempo_altstep->valuedouble;
  }
  else return 0.01;
}

bool RSI_Preferences::WantAutoEjectTrack() const
{
  const cJSON *auto_eject_track = NULL;
  auto_eject_track = cJSON_GetObjectItemCaseSensitive(m_pf, "auto_eject_track");
  if (cJSON_IsTrue(auto_eject_track)) return true;
  else if (cJSON_IsFalse(auto_eject_track)) return false;
  else return false;
}

bool RSI_Preferences::WantTrackRepeat() const
{
  const cJSON *track_repeat = NULL;
  track_repeat = cJSON_GetObjectItemCaseSensitive(m_pf, "track_repeat");
  if (cJSON_IsTrue(track_repeat)) return true;
  else if (cJSON_IsFalse(track_repeat)) return false;
  else return false;
}

double RSI_Preferences::GetVolumeStep() const
{
  const cJSON *volume_step = NULL;
  volume_step = cJSON_GetObjectItemCaseSensitive(m_pf, "volume_step");
  if (cJSON_IsNumber(volume_step))
  {
    return volume_step->valuedouble;
  }
  else return 2.0;
}

bool RSI_Preferences::AskExit() const
{
  const cJSON *ask_exit = NULL;
  ask_exit = cJSON_GetObjectItemCaseSensitive(m_pf, "ask_exit");
  if (cJSON_IsTrue(ask_exit)) return true;
  else if (cJSON_IsFalse(ask_exit)) return false;
  else return false;
}

int RSI_Preferences::GetBackgroundColor() const
{
  const cJSON *bg_color = NULL;
  bg_color = cJSON_GetObjectItemCaseSensitive(m_pf, "background_color");
  if (cJSON_IsString(bg_color) && (bg_color->valuestring != NULL))
  {
    int len = (int)strlen(bg_color->valuestring);
    if (len != 6) return 0x000000;
    int bgc = (int)strtol(bg_color->valuestring, NULL, 16);
    if (bgc < 0x000000 || bgc > 0xFFFFFF) return 0x000000;
    return bgc;
  }
  else return 0x000000;
}

int RSI_Preferences::GetTextColor() const
{
  const cJSON *txt_color = NULL;
  txt_color = cJSON_GetObjectItemCaseSensitive(m_pf, "text_color");
  if (cJSON_IsString(txt_color) && (txt_color->valuestring != NULL))
  {
    int len = (int)strlen(txt_color->valuestring);
    if (len != 6) return 0xC0C0C0;
    int txtc = (int)strtol(txt_color->valuestring, NULL, 16);
    if (txtc < 0x000000 || txtc > 0xFFFFFF) return 0xC0C0C0;
    return txtc;
  }
  else return 0xC0C0C0;
}

bool RSI_Preferences::WantEBUR128() const
{
  const cJSON *ebur128_normalization = NULL;
  ebur128_normalization = cJSON_GetObjectItemCaseSensitive(m_pf, "ebur128_normalization");
  if (cJSON_IsTrue(ebur128_normalization)) return true;
  else if (cJSON_IsFalse(ebur128_normalization)) return false;
  else return false;
}

bool RSI_Preferences::WantDownwardOnly() const
{
  const cJSON *ebur128_downward_only = NULL;
  ebur128_downward_only = cJSON_GetObjectItemCaseSensitive(m_pf, "ebur128_downward_only");
  if (cJSON_IsTrue(ebur128_downward_only)) return true;
  else if (cJSON_IsFalse(ebur128_downward_only)) return false;
  else return true;
}

double RSI_Preferences::GetEBUR128LUFS() const
{
  const cJSON *ebur128_reference = NULL;
  ebur128_reference = cJSON_GetObjectItemCaseSensitive(m_pf, "ebur128_reference");
  if (cJSON_IsNumber(ebur128_reference))
  {
    if (ebur128_reference->valueint >= 0 &&
      ebur128_reference->valueint <= 4)
    {
      switch (ebur128_reference->valueint)
      {
      case 0: return -23.0;
      case 1: return -18.0;
      case 2: return -16.0;
      case 3: return -14.0;
      case 4: return -11.0;
      default: return -23.0;
      }
    }
    else return -23.0;
  }
  else return -23.0;
}

int RSI_Preferences::GetEBUR128Mode() const
{
  const cJSON *ebur128_mode = NULL;
  ebur128_mode = cJSON_GetObjectItemCaseSensitive(m_pf, "ebur128_mode");
  if (cJSON_IsNumber(ebur128_mode))
  {
    if (ebur128_mode->valueint >= 0 &&
      ebur128_mode->valueint <= 5)
    {
      switch (ebur128_mode->valueint)
      {
      case 0: return EBUR128_MODE_M;
      case 1: return EBUR128_MODE_M | EBUR128_MODE_S;
      case 2: return EBUR128_MODE_M | EBUR128_MODE_S | EBUR128_MODE_I;
      case 3: return EBUR128_MODE_M | EBUR128_MODE_S | EBUR128_MODE_I |
                EBUR128_MODE_LRA;
      case 4: return EBUR128_MODE_M | EBUR128_MODE_S | EBUR128_MODE_I |
                EBUR128_MODE_LRA | EBUR128_MODE_SAMPLE_PEAK;
      case 5: return EBUR128_MODE_M | EBUR128_MODE_S | EBUR128_MODE_I |
                EBUR128_MODE_LRA | EBUR128_MODE_SAMPLE_PEAK |
                EBUR128_MODE_TRUE_PEAK;
      //case 6: return EBUR128_MODE_M | EBUR128_MODE_S | EBUR128_MODE_I |
      //          EBUR128_MODE_LRA | EBUR128_MODE_SAMPLE_PEAK |
      //          EBUR128_MODE_TRUE_PEAK | EBUR128_MODE_HISTOGRAM;
      default: return EBUR128_MODE_I;
      }
    }
    else return EBUR128_MODE_I;
  }
  else return EBUR128_MODE_I;
}

bool RSI_Preferences::WantPreserveCurrentDirectory() const
{
  const cJSON *preserve_current_directory = NULL;
  preserve_current_directory = cJSON_GetObjectItemCaseSensitive(m_pf, "preserve_current_directory");
  if (cJSON_IsTrue(preserve_current_directory)) return true;
  else if (cJSON_IsFalse(preserve_current_directory)) return false;
  else return true;
}

int RSI_Preferences::GetMainDialogFontSize() const
{
  const cJSON *main_dialog_font_size = NULL;
  main_dialog_font_size = cJSON_GetObjectItemCaseSensitive(m_pf, "main_dialog_font_size");
  if (cJSON_IsNumber(main_dialog_font_size))
  {
    if (main_dialog_font_size->valueint >= 8 &&
      main_dialog_font_size->valueint <= 72)
    {
      return main_dialog_font_size->valueint;
    }
    else return 20;
  }
  else return 20;
}

int RSI_Preferences::GetStatsDialogFontSize() const
{
  const cJSON *stats_dialog_font_size = NULL;
  stats_dialog_font_size = cJSON_GetObjectItemCaseSensitive(m_pf, "stats_dialog_font_size");
  if (cJSON_IsNumber(stats_dialog_font_size))
  {
    if (stats_dialog_font_size->valueint >= 8 &&
      stats_dialog_font_size->valueint <= 72)
    {
      return stats_dialog_font_size->valueint;
    }
    else return 20;
  }
  else return 20;
}

void RSI_Preferences::GetMediaLibraryPaths(WDL_PtrList_DeleteOnDestroy<WDL_FastString> **paths) const
{
  const cJSON *media_library_path = NULL;
  const cJSON *media_library_paths = NULL;
  WDL_PtrList_DeleteOnDestroy<WDL_FastString> *mlp = new WDL_PtrList_DeleteOnDestroy<WDL_FastString>;
  media_library_paths = cJSON_GetObjectItemCaseSensitive(m_pf, "media_library_paths");
  cJSON_ArrayForEach(media_library_path, media_library_paths)
  {
    if (cJSON_IsString(media_library_path) && (media_library_path->valuestring != NULL))
    {
      mlp->Add(new WDL_FastString(media_library_path->valuestring));
    }
  }
  *paths = mlp;
}

int RSI_Preferences::GetMediaLibraryQueryLimit() const
{
  const cJSON *media_library_query_limit = NULL;
  media_library_query_limit = cJSON_GetObjectItemCaseSensitive(m_pf, "media_library_query_limit");
  if (cJSON_IsNumber(media_library_query_limit))
  {
    return media_library_query_limit->valueint;
  }
  else return 300;
}
