#include "mm-config.h"

/*获取配置文件key-value*/
gchar* mm_get_config_value (const gchar *file_path, gchar *section, gchar *key)
{
  GKeyFile *key_file;
  GError *error = NULL;
  gchar *value;
  //创建一个Gkeyfile对象
  key_file = g_key_file_new();

  //加载配置文件
  if(!g_key_file_load_from_file(key_file, file_path, G_KEY_FILE_NONE, &error))
  {
    g_error_free (error);
    g_key_file_free(key_file);
    value = NULL;
    return value;
  }

  //获取当前文件中key的value
  value = g_key_file_get_string (key_file, section, key, &error);
  if(error)
  {
    value = NULL;
  } 
  g_error_free (error);
  return value;
}
/*设置配置文件key-value*/
gboolean mm_set_config_value (const gchar *file_path, gchar *section, gchar *key, gchar *value)
{

  // 配置文件是否存在，不存在初始化创建
  GFile *file;
  GFileInfo *info;
  GKeyFile *key_file;
  GError *error = NULL;

  file = g_file_new_for_path (file_path);
  info = g_file_query_info(file, G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME, G_FILE_QUERY_INFO_NONE, NULL, &error);
  if (info == NULL)
  {
    const gchar *default_conf = "[boot]\nboot=normal\n";
    if (!g_file_replace_contents(file, default_conf, -1, NULL, FALSE, G_FILE_CREATE_NONE, NULL, NULL, &error))
    {
      g_info("1111.");
      return FALSE;
    }
  }
  g_object_unref(info);
  g_object_unref(file);
  
  //创建一个Gkeyfile对象
  key_file = g_key_file_new();

  //加载配置文件
  if(!g_key_file_load_from_file(key_file, file_path, G_KEY_FILE_NONE, &error))
  {
    if (error->code == G_FILE_ERROR_NOENT)
    {
      /*文件不存在，直接创建文件*/
      g_info("file does exits.");
    }else
    {
      g_info("load conf file error.");
    }
  }
  

  if (!g_key_file_has_group(key_file, section))
  {
    g_key_file_set_comment(key_file, section, key, "new group", &error);
  }
  
  if (g_key_file_has_key(key_file, section, key, NULL))
  {
    g_key_file_set_string (key_file, section, key, value);
  }else
  {
    g_key_file_set_string (key_file, section, key, value);
  }
  
  
  if (!g_key_file_save_to_file (key_file, file_path, &error))
  {
    g_printerr("save err %s \n",error->message);
    g_info("1112.");
    //g_error_free(error);
    return FALSE;
  }

  return TRUE;
}