/* m3u.c
 * Copyright (C) 2005 Sylvain Cresto <scresto@gmail.com>
 *
 * This file is part of graveman!
 *
 * graveman! 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, or
 * (at your option) any later version.
 *
 * graveman! 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 program; see the file COPYING. If not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
 * MA 02111-1307, USA.
 *
 * URL: http://www.nongnu.org/graveman/
 *
 */

#include "graveman.h"

#define EXT_M3U "#EXTM3U"
#define EXT_INF "#EXTINF;"
#define HTTP "http://"

/* import d'un fichier */
gboolean m3u_import(gchar *Afilename, Tgrave *Ag, gboolean Anew, GError **Aerror)
{
  FILE *Lfic;
  gchar *s;
  gchar Lbuf[_BUF_SIZE];
  gchar Ltmp[MAXPATHLEN];
  gchar *Lrepertoire;
  GtkTreeModel *Ltreemodel = gtk_tree_view_get_model(GTK_TREE_VIEW(sc_grave_get_widget(Ag, "LISTEAUDIO")));

  if (!(Lfic = fopen(Afilename, "r"))) {
    s = g_strdup_printf(_("Cannot import %s: %s"), Afilename, g_strerror(errno));
    g_set_error(Aerror, G_FILE_ERROR, g_file_error_from_errno(errno), s, g_strerror(errno)); 
    g_free(s);
    return FALSE;
  } 

  if (Anew) clear_list_audio(Ag);
  
  Lrepertoire = g_path_get_dirname(Afilename);

  while (fgets(Lbuf, _BUF_SIZE-1, Lfic)) {
    Lbuf[_BUF_SIZE-1] = 0;

    sc_chomp(Lbuf);

    if (*Lbuf == 0) continue;
    if (*Lbuf == '#') {
      /* commentaire */
      continue;
    } else {
      /* fichier chemin local ou non */
      if (!strncmp(Lbuf, HTTP, strlen(HTTP))) 
        continue; /* on ignore les http pour le moment .. */
      
      if (strchr(Lbuf, '/')) {
        g_strlcpy(Ltmp, Lbuf, MAXPATHLEN-1);
      } else {
        g_snprintf(Ltmp, MAXPATHLEN-1, "%s/%s", Lrepertoire, Lbuf);
      }
      if (g_file_test(Lbuf, G_FILE_TEST_EXISTS)) {
        _add_a_piste(Lbuf, GTK_LIST_STORE(Ltreemodel), Ag);
      }
    }
  }
  
  fclose(Lfic);

  g_free(Lrepertoire);
  
  return TRUE;
}

/*
 * vim:et:ts=8:sts=2:sw=2
 */
