/*****************************************************************
 * gmerlin - a general purpose multimedia framework and applications
 *
 * Copyright (c) 2001 - 2012 Members of the Gmerlin project
 * gmerlin-general@lists.sourceforge.net
 * http://gmerlin.sourceforge.net
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * *****************************************************************/

#include "renderer.h"

#include <gmerlin/cmdline.h>
#include <gmerlin/player.h>
#include <gmerlin/bggavl.h>
#include <gmerlin/utils.h>

#include <signal.h>
#include <errno.h>

#include <string.h>
#include <unistd.h>

#define LOG_DOMAIN "gmerlin-renderer"


const bg_parameter_info_t * renderer_params;
bg_cfg_section_t * renderer_section = NULL;

bg_cfg_section_t * cfg_section = NULL;

char * save_config = NULL;
char * config_file = NULL;
char * state_file = NULL;

bg_cfg_ctx_t * cfg = NULL;

static bg_cfg_section_t * load_config_file(const char * name)
  {
  xmlNodePtr node;
  xmlDocPtr xml_doc;
  bg_cfg_section_t * ret;
  
  xml_doc = bg_xml_parse_file(name, 1);

  if(!xml_doc)
    return NULL;
  
  node = xml_doc->children;
  
  if(BG_XML_STRCMP(node->name, "RENDERERCONFIG"))
    {
    xmlFreeDoc(xml_doc);
    return NULL;
    }
  ret = bg_cfg_section_create(NULL);
  bg_cfg_xml_2_section(xml_doc, node, ret);
  xmlFreeDoc(xml_doc);
  return ret;
  }

static void save_config_file(const bg_cfg_section_t * s, const char * filename)
  {
  xmlDocPtr  xml_doc;
  xmlNodePtr node;
  xml_doc = xmlNewDoc((xmlChar*)"1.0");
  node = xmlNewDocRawNode(xml_doc, NULL, (xmlChar*)"RENDERERCONFIG", NULL);
  
  xmlDocSetRootElement(xml_doc, node);

  bg_cfg_section_2_xml(s, node);

  bg_xml_save_file(xml_doc, filename, 1);
  xmlFreeDoc(xml_doc);
  }

static void opt_c(void * data, int * argc, char *** _argv, int arg)
  {
  if(arg >= *argc)
    {
    fprintf(stderr, "Option -c requires an argument\n");
    exit(-1);
    }

  config_file = (*_argv)[arg];

  gavl_log(GAVL_LOG_INFO, LOG_DOMAIN, "Using config file %s", config_file);
  
  if(!cfg_section)
    cfg_section = load_config_file(config_file);
  else
    {
    bg_cfg_section_t * tmp;
    
    if((tmp = load_config_file(config_file)))
      {
      bg_cfg_ctx_array_clear_sections(cfg);
      
      bg_cfg_section_transfer(tmp, cfg_section);
      bg_cfg_ctx_array_create_sections(cfg, cfg_section);
      bg_cfg_section_destroy(tmp);
      }
    }
  }

static void opt_state(void * data, int * argc, char *** _argv, int arg)
  {
  if(arg >= *argc)
    {
    fprintf(stderr, "Option -s requires an argument\n");
    exit(-1);
    }
  state_file = (*_argv)[arg];
  gavl_log(GAVL_LOG_INFO, LOG_DOMAIN, "Using state file %s", state_file);
  }

static void opt_r(void * data, int * argc, char *** _argv, int arg)
  {
  if(arg >= *argc)
    {
    fprintf(stderr, "Option -r requires an argument\n");
    exit(-1);
    }

  if(!bg_cmdline_apply_options(renderer_section,
                               NULL,
                               NULL,
                               renderer_params,
                               (*_argv)[arg]))
    exit(-1);
  bg_cmdline_remove_arg(argc, _argv, arg);
  }

static bg_cmdline_arg_t global_options[] =
  {
    {
      .arg =         "-sc",
      .help_arg =    "<file>",
      .help_string = TRS("Save config to file"),
      .argv =        &save_config,
    },
    {
      .arg =         "-c",
      .help_arg =    "<file>",
      .help_string = TRS("Load config from file"),
      .callback =    opt_c,
    },
    {
      .arg =         "-s",
      .help_arg =    "<file>",
      .help_string = TRS("Use file to save the player state"),
      .callback =    opt_state,
    },
    {
      .arg =         "-r",
      .help_arg =    "<options>",
      .help_string = TRS("Renderer options"),
      .callback =    opt_r,
    },
    {
      .arg =         "-i",
      .help_arg =    "<options>",
      .help_string = TRS("Input options"),
    },
    {
      .arg =         "-aud",
      .help_arg =    "<options>",
      .help_string = TRS("Audio options"),
    },
    {
      .arg =         "-vid",
      .help_arg =    "<options>",
      .help_string = TRS("Video options"),
    },
    {
      .arg =         "-af",
      .help_arg =    "<options>",
      .help_string = TRS("Audio filter"),
    },
    {
      .arg =         "-vf",
      .help_arg =    "<options>",
      .help_string = TRS("Video filter"),
    },
    {
      .arg =         "-vis",
      .help_arg =    "<options>",
      .help_string = TRS("Audio visualization"),
    },
    {
      .arg =         "-osd",
      .help_arg =    "<options>",
      .help_string = TRS("OSD Options"),
    },
    { /* End */ }
  };

const bg_cmdline_app_data_t app_data =
  {
    .package =  PACKAGE,
    .version =  VERSION,
    .name =     "gmerlin-renderer",
    .long_name = TRS("Gmerlin media renderer"),
    .synopsis = TRS("[options]\n"),
    .help_before = TRS("Gmerlin Mediarenderer\n"),
    .args = (bg_cmdline_arg_array_t[]) { { TRS("Options"), global_options },
                                       {  } },
    .files = (bg_cmdline_ext_doc_t[])
    { { "~/.gmerlin/plugins.xml",
        TRS("Cache of the plugin registry (shared by all applications)") },
      { "~/.gmerlin/generic/cfg.xml",
        TRS("Default plugin parameters are read from there. Use gmerlin_plugincfg to change them.") },
      { /* End */ }
    },
    
  };


int main(int argc, char ** argv)
  {
  renderer_t s;
  int ret = EXIT_FAILURE;
  
  bg_handle_sigint();
  signal(SIGPIPE, SIG_IGN);
  
  renderer_init(&s);

  cfg_section =
    bg_cfg_section_create(NULL);
  
  cfg = bg_embed_player_get_cfg(s.p);

  bg_cfg_ctx_array_create_sections(cfg, cfg_section);
  
  renderer_params = renderer_get_parameters(&s);
  
  bg_cmdline_arg_set_parameters(global_options, "-r",
                                renderer_params);

  bg_cmdline_arg_set_cfg_ctx(global_options, "-i",   cfg + BG_PLAYER_CFG_INPUT);
  bg_cmdline_arg_set_cfg_ctx(global_options, "-aud", cfg + BG_PLAYER_CFG_AUDIO);
  bg_cmdline_arg_set_cfg_ctx(global_options, "-vid", cfg + BG_PLAYER_CFG_VIDEO);
  bg_cmdline_arg_set_cfg_ctx(global_options, "-oa",  cfg + BG_PLAYER_CFG_AUDIOPLUGIN);
  bg_cmdline_arg_set_cfg_ctx(global_options, "-ov",  cfg + BG_PLAYER_CFG_VIDEOPLUGIN);
  bg_cmdline_arg_set_cfg_ctx(global_options, "-sub", cfg + BG_PLAYER_CFG_SUBTITLE);
  bg_cmdline_arg_set_cfg_ctx(global_options, "-af",  cfg + BG_PLAYER_CFG_AUDIOFILTER);
  bg_cmdline_arg_set_cfg_ctx(global_options, "-vf",  cfg + BG_PLAYER_CFG_VIDEOFILTER);
  bg_cmdline_arg_set_cfg_ctx(global_options, "-vis", cfg + BG_PLAYER_CFG_VISUALIZATION);
  bg_cmdline_arg_set_cfg_ctx(global_options, "-osd", cfg + BG_PLAYER_CFG_OSD);
  
  bg_cmdline_init(&app_data);
  bg_cmdline_parse(global_options, &argc, &argv, NULL);
  
  renderer_section = bg_cfg_section_find_subsection(cfg_section, "renderer");
  bg_cfg_section_apply(renderer_section,
                       renderer_params,
                       renderer_set_parameter,
                       &s);

  
  
  /* Initialize application state */
  
  if(!renderer_start(&s, state_file))
    goto fail;
  
  bg_cfg_ctx_set_sink_array(cfg, s.player_ctrl->cmd_sink);
  
  bg_cfg_ctx_apply_array(cfg);
  
  if(save_config)
    {
    bg_cfg_section_get(renderer_section, renderer_params, renderer_get_parameter, &s);
    save_config_file(cfg_section, save_config);
    }
  
  while(renderer_iteration(&s))
    {
    if(bg_got_sigint())
      break;

    if(bg_embed_player_get_error(s.p))
      {
      gavl_log(GAVL_LOG_ERROR, LOG_DOMAIN, "Got internal error, exiting");
      goto fail;
      }
    }
  
  ret = EXIT_SUCCESS;
  fail:

  //  bg_msg_hub_disconnect_sink(s.player_ctrl->evt_hub, sink);
  renderer_cleanup(&s);
  

  return ret;
  }
