//ff_m3u.c:

/*
 *      Copyright (C) Philipp 'ph3-der-loewe' Schafft - 2009-2014
 *
 *  This file is part of RoarAudio PlayList Daemon,
 *  a playlist management daemon for RoarAudio.
 *  See README for details.
 *
 *  This file is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License version 3
 *  as published by the Free Software Foundation.
 *
 *  RoarAudio 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 software; see the file COPYING.  If not, write to
 *  the Free Software Foundation, 51 Franklin Street, Fifth Floor,
 *  Boston, MA 02110-1301, USA.
 *
 */

#include "rpld.h"

int ff_m3u_pl_export(struct fformat_handle * handle, struct roar_vio_calls * vio, struct rpld_playlist  * pl) {
 const char * artist;
 struct rpld_playlist_entry * cur = rpld_pl_get_first(pl);

 (void)handle;

 roar_vio_printf(vio, "#EXTM3U\n");

 while ( cur != NULL ) {
  artist = cur->meta.artist;

  if ( *artist == 0 )
   artist = cur->meta.performer;

  roar_vio_printf(vio, "#EXTINF:%lu,%s - %s\n", (unsigned long)cur->length, artist, cur->meta.title);

  roar_vio_printf(vio, "%s\n", rpld_ple_get_filename(cur, -1, NULL));

  cur = cur->list.next;
 }

 return 0;
}

int ff_m3u_pl_import(struct fformat_handle * handle, struct roar_vio_calls * vio, struct rpld_playlist  * pl) {
 struct rpld_playlist_entry * plent = NULL;
 char buf[1024];
 char * s, * delm;
 size_t len;

 (void)handle;

 while ((s = roar_vio_fgets(vio, buf, 1024)) != NULL ) {
  len = strlen(s);

  for (s += len - 1; *s == '\r' || *s == '\n'; s--)
   *s = 0;

  if ( !*buf )
   continue;

  if ( plent == NULL )
   if ( (plent = rpld_ple_new()) == NULL )
    return -1;

  if ( buf[0] == '#' ) {
   if ( !strcmp(buf, "#EXTM3U") )
    continue;

   if ( !strncmp(buf, "#EXTINF:", 8) ) {
    s = strstr(buf+8, ",");

    if ( s != NULL ) {
     *s = 0;
      s++;
    }

    if ( !strcmp(buf+8, "-1") ) {
     plent->length = 0;
    } else {
     plent->length = atol(buf+8);
    }

    if ( (delm = strstr(s, " - ")) == NULL ) {
     strncpy(plent->meta.title, s, sizeof(plent->meta.title));
    } else {
     *delm  = 0;
      delm += 3;
     strncpy(plent->meta.artist, s,    sizeof(plent->meta.artist));
     strncpy(plent->meta.title,  delm, sizeof(plent->meta.title));
    }
   }
   continue;
  }

  rpld_ple_push_filename(plent, buf, RPLD_TYPE_UNKNOWN, 1);

  rpld_pl_push(pl, plent);

  plent = NULL;
 }

 if ( plent != NULL )
  rpld_ple_free(plent);

 return 0;
}

//ll
