#include "ttxtsubschannelsettings.h"

#include <vdr/channels.h>
#include <vdr/plugin.h>
#include <vdr/tools.h>

class cTtxtSubsChannelSettings *cTtxtSubsChannelSettings::mInstance=NULL;

cTtxtSubsChannelSettings::cTtxtSubsChannelSettings(const char *configDir)
{
    mChannelSettingsFileName = strdup(AddDirectory(configDir,
      "channelsettings.dat"));
    LoadSettings();
}

cTtxtSubsChannelSettings &cTtxtSubsChannelSettings::CreateInstance(
  const char *configDir)
{
    if (!mInstance) 
    {
        mInstance = new cTtxtSubsChannelSettings(configDir);
    }
    return *mInstance;
}

cTtxtSubsChannelSettings &cTtxtSubsChannelSettings::GetInstance()
{
    if (!mInstance) 
    {
        throw "create an instance of cTtxtSubsChannelSettings first";
    }
    return *mInstance;
}

TtxtSubsChannelSetting cTtxtSubsChannelSettings::GetChannelSetting(
 int channelId)
{
    cSettingsContainer::iterator iter;
  
    iter = mSettings.find(channelId);
    if(iter != mSettings.end()) 
    {
        return iter->second;
    } else 
    {
        // return default page settings (AUTO, PAGE=0)
        TtxtSubsChannelSetting ret;
        ret.PageMode   = 0;
        ret.PageNumber = 0;
        return ret;
    }
}

void cTtxtSubsChannelSettings::SetChannelSetting(int channelId, int PageMode,
  int PageNumber)
{
    TtxtSubsChannelSetting setting;
    setting.PageMode = PageMode;
    setting.PageNumber = PageNumber;

    mSettings[channelId] = setting;
    SaveSettings();
}

void cTtxtSubsChannelSettings::LoadSettings()
{
    int channelId;
  
    FILE *settingsFile = fopen(mChannelSettingsFileName, "r");
    if (settingsFile)
    {
        while (!feof(settingsFile))
        {
            TtxtSubsChannelSetting setting;
            int read = fscanf(settingsFile, "%d,%d,%d\n", &channelId,
              &setting.PageMode, &setting.PageNumber);
            if (read == 3)
            {
                mSettings[channelId] = setting;
            }
        }
        fclose(settingsFile);
    }
}

void cTtxtSubsChannelSettings::SaveSettings()
{
    FILE *settingsFile = fopen(mChannelSettingsFileName, "w+");
    if (settingsFile)
    {
        cSettingsContainer::iterator iter;
        for (iter=mSettings.begin(); iter != mSettings.end(); iter++)
        {
            int channelId = (*iter).first;    
            TtxtSubsChannelSetting setting = (*iter).second;
            fprintf(settingsFile, "%d,%d,%d\n", channelId, setting.PageMode,
              setting.PageNumber);
        }
        fclose(settingsFile);
    }
}
