/*
 * Audacious: A cross-platform multimedia player
 * Copyright (c) 2006 William Pitcock, Tony Vroon, George Averill,
 *                    Giacomo Lozito, Derek Pomery and Yoshiki Yazawa.
 *
 * 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, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */

/* #define AUD_DEBUG 1 */

#include <glib.h>
#include <string.h>
#include <glib.h>
#include <glib/gprintf.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/errno.h>

#include <audacious/main.h>
#include <audacious/util.h>
#include <audacious/playlist.h>
#include <audacious/playlist_container.h>
#include <audacious/plugin.h>
#include <audacious/strings.h>

static gchar *
str_replace_char(gchar * str, gchar old, gchar new)
{
    gchar *match;

    g_return_val_if_fail(str != NULL, NULL);

    match = str;
    while ((match = strchr(match, old)))
        *match = new;

    return str;
}

static gchar *
str_replace_drive_letter(gchar * str)
{
    gchar *match, *match_end;

    g_return_val_if_fail(str != NULL, NULL);

    while ((match = strstr(str, ":\\"))) {
        match--;
        match_end = match + 3;
        *match++ = '/';
        while (*match_end)
            *match++ = *match_end++;
        *match = 0; /* the end of line */
    }

    return str;
}

static gchar *
_convert_dos_path(gchar * path)
{
    g_return_val_if_fail(path != NULL, NULL);

    /* replace drive letter with '/' */
    str_replace_drive_letter(path);

    /* replace '\' with '/' */
    str_replace_char(path, '\\', '/');

    return path;
}

static gchar *
_construct_uri(gchar *string, const gchar *playlist_name) // uri, path and anything else
{
    gchar *filename = g_strdup(string);
    gchar *tmp, *path, *tfile;
    gchar *uri = NULL;

    /* try to translate dos path */
    _convert_dos_path(filename); /* in place replacement */

    /* convert backslash to slash */
    while ((tmp = strchr(filename, '\\')) != NULL)
        *tmp = '/';

    // make full path uri here
    // case 1: filename is raw full path or uri
    if (filename[0] == '/' || strstr(filename, "://")) {
        uri = g_filename_to_uri(filename, NULL, NULL);
        if(!uri) {
            uri = g_strdup(filename);
        }
        g_free(filename);
    }

    // case 2: filename is not raw full path nor uri, playlist path is full path
    // make full path by replacing last part of playlist path with filename. (using g_build_filename)
    else if (playlist_name[0] == '/' || strstr(playlist_name, "://")) {
        path = g_strdup(playlist_name);
        tmp = strrchr(path, '/'); *tmp = '\0';
        tmp = g_build_filename(path, filename, NULL);
        g_free(path); g_free(filename);

        // make sure we pass a 100% valid URI into the core.
        tfile = g_filename_from_uri(tmp, NULL, NULL);
        uri = g_filename_to_uri(tfile, NULL, NULL);
        g_free(tfile);

        if (uri)
            g_free(tmp);
        else
            uri = tmp;
    }

    // case 3: filename is not raw full path nor uri, playlist path is not full path
    // just abort.
    else {
        g_free(filename);
        return NULL;
    }

    return uri;
}

static void
playlist_load_pls(const gchar * filename, gint pos)
{
    guint i, count, added_count = 0;
    gchar line_key[10], title_key[10];
    gchar *line, *title;
    Playlist *playlist = aud_playlist_get_active();

    g_return_if_fail(filename != NULL);

    if (!aud_str_has_suffix_nocase(filename, ".pls"))
        return;

    INIFile *inifile = aud_open_ini_file(filename);
    if (!(line = aud_read_ini_string(inifile, "playlist", "NumberOfEntries")))
    {
        aud_close_ini_file(inifile);
        return;
    }

    count = atoi(line);
    g_free(line);

    for (i = 1; i <= count; i++) {
        g_snprintf(line_key, sizeof(line_key), "File%d", i);
        if ((line = aud_read_ini_string(inifile, "playlist", line_key)))
        {
            gchar *uri = _construct_uri(line, filename);
            g_free(line);

            /* add file only if valid uri has been constructed */
            if (uri) {
                if (aud_cfg->use_pl_metadata)
                {
                    g_snprintf(title_key, sizeof(title_key), "Title%d", i);

                    if ((title = aud_read_ini_string(inifile, "playlist", title_key)))
                        aud_playlist_load_ins_file(playlist, uri, filename, pos, title, -1);
                    else
                        aud_playlist_load_ins_file(playlist, uri, filename, pos, NULL, -1);
                }
                else
                    aud_playlist_load_ins_file(playlist, uri, filename, pos, NULL, -1);

                added_count++;

                if (pos >= 0)
                    pos++;
            }
            g_free(uri);
        }
    }

    aud_close_ini_file(inifile);
}

static void
playlist_save_pls(const gchar *filename, gint pos)
{
    gchar *uri = g_filename_to_uri(filename, NULL, NULL);
    GList *node;
    VFSFile *file = aud_vfs_fopen(uri, "wb");
    Playlist *playlist = aud_playlist_get_active();

    g_return_if_fail(file != NULL);
    g_return_if_fail(playlist != NULL);

    aud_vfs_fprintf(file, "[playlist]\n");
    aud_vfs_fprintf(file, "NumberOfEntries=%d\n", aud_playlist_get_length(playlist));

    PLAYLIST_LOCK(playlist);

    for (node = playlist->entries; node; node = g_list_next(node)) {
        PlaylistEntry *entry = PLAYLIST_ENTRY(node->data);
        gchar *fn;

        if (aud_vfs_is_remote(entry->filename))
            fn = g_strdup(entry->filename);
        else
            fn = g_filename_from_uri(entry->filename, NULL, NULL);

        aud_vfs_fprintf(file, "File%d=%s\n", g_list_position(playlist->entries, node) + 1,
                    fn);

        g_free(fn);
    }

    PLAYLIST_UNLOCK(playlist);

    aud_vfs_fclose(file);
}

PlaylistContainer plc_pls = {
    .name = "Winamp .pls Playlist Format",
    .ext = "pls",
    .plc_read = playlist_load_pls,
    .plc_write = playlist_save_pls,
};

static void init(void)
{
    aud_playlist_container_register(&plc_pls);
}

static void cleanup(void)
{
    aud_playlist_container_unregister(&plc_pls);
}

DECLARE_PLUGIN(pls, init, cleanup, NULL, NULL, NULL, NULL, NULL, NULL);
