/*
    This file is part of audtty, copyright 2008-2010 Chris Taylor.

    audtty 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.

    audtty 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 audtty; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

#include <audacious/audctrl.h>
#include <stdlib.h>
#include <ncursesw/curses.h>
#include <libgen.h>
#define __USE_GNU // to get strcasestr
#include <string.h>
#include "curses_printf.h"
#include "kbd_constants.h"
#include "main.h"
#include "playlist.h"
#include "dbus.h"
#include <time.h>
#include <glib.h>

extern struct timespec interval;
extern playlist list;
extern windows wins;

void playlist_addurl(void)
{
	gint len = 0;

	gchar buffer[512];

	buffer[0] = '\0';

	while (true) {
		gint c;
		gchar *uri = NULL;

		if (wins.term_resized == true) {
			wins.term_resized = false;
			resize_windows();
		}

		while((c = getch()) != ERR) {
			switch (c) {
				case ESCAPE:
					return;
					break;
				case ENTER:
					uri=g_filename_to_uri(buffer, NULL, NULL);
					audacious_remote_playlist_add_url_string(dbus_proxy,  uri);
					return;
					break;
				case KEY_BACKSPACE:
					if (len == 0) break;
					buffer[--len] = '\0';
					break;
				default:
					if (len == 513) break;
					if (c < 32) break;
					buffer[len] = c;
					buffer[++len] = '\0';
					break;
			}
		}

		gint x, y;
		mvwaddnstrf(wins.status, 0, 0, "Adding URL: %s", -1, buffer);
		getyx(wins.status, y, x);
		wclrtoeol(wins.status);
		mvwchgat(wins.status, 0, 0, -1, A_BOLD, 1, NULL);
		wnoutrefresh(wins.status);

		doupdate();
		nanosleep(&interval, NULL);
                g_free(uri);
	}
}