#!/usr/bin/env python
# -*- coding: iso-8859-15 -*-

"""
    Raspymc is a multimedia centre exposed via a http server built with bottlepy
    Copyright (C) 2013  Giancarlo Fringuello

    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 3 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/>.
"""

import os, inspect, ConfigParser, pickle

from utils import *
from logger import*
from track_obj import *

CNF_SERVER_PATH	= sys.path[0]
CNF_FOLDER_PATH = "" 
CNF_PLAYLIST_PATH	= CNF_SERVER_PATH + "/config/playlist.pkl"
CNF_FOLDER_PATH = CNF_SERVER_PATH + "/config/"
CNF_CONFIG_FILE = CNF_FOLDER_PATH + "config.ini"
	
#
# Loads the saved playlist from file
def get_playlist():
	


def store_playlist(p_list):
	log(LOG_INFO, inspect.currentframe().f_lineno, "conf_manager.py::store_playlist()")
	try:
		with open(CNF_PLAYLIST_PATH, 'wb') as l_output:
			pickle.dump(p_list, l_output, pickle.HIGHEST_PROTOCOL)
	except:
		log(LOG_WARNING, inspect.currentframe().f_lineno, "conf_manager.py::store_playlist()", "unexisting playlist file: " + CNF_PLAYLIST_PATH)

#
# Loads the configuration from file
def get_folder_path():
	log(LOG_INFO, inspect.currentframe().f_lineno, "conf_manager.py::load_configuration()")
	global CNF_FOLDER_PATH
	global CNF_PLAYLIST_PATH
	global SERVER_PATH

	l_config_parser = ConfigParser.ConfigParser()

	l_clean_configuration = False

	if not os.path.isdir(CNF_FOLDER_PATH): # if config directory does not exist, create it
		os.makedirs(CNF_FOLDER_PATH)
		log(LOG_WARNING, inspect.currentframe().f_lineno, "conf_manager.py::load_configuration()", CNF_FOLDER_PATH + " did not exist, it has been created")
    
	if os.path.isfile(CNF_CONFIG_FILE):
		try:
			l_config_parser.read(CNF_CONFIG_FILE)
			if l_config_parser.has_section("PATH"):
				if l_config_parser.has_option("PATH", "CNF_FOLDER_PATH"):
					CNF_FOLDER_PATH = l_config_parser.get("PATH","CNF_FOLDER_PATH")
				else:
					l_clean_configuration = True
			else:
				# if section does not exist
				l_clean_configuration = True
				log(LOG_VERBOSE, inspect.currentframe().f_lineno, "conf_manager.py::load_configuration()", "unable to load CNF_FOLDER_PATH, using home as default, new config.ini will be generated.")
		except:
			# if unable to read file (e.g. file damaged)
			l_clean_configuration = True
			log(LOG_WARNING, inspect.currentframe().f_lineno, "conf_manager.py::load_configuration()",  "exception: unable to load CNF_FOLDER_PATH from " + CNF_CONFIG_FILE + ", using home path as default, new config.ini will be generated.")
	else:
		l_clean_configuration = True
		log(LOG_WARNING, inspect.currentframe().f_lineno, "conf_manager.py::load_configuration()", "no configuration file found,  new config.ini will be generated.")
  
	if l_clean_configuration:
		# cleanup config file
		for l_section in l_config_parser.sections():
			l_config_parser.remove_section(l_section)
		l_config_parser.add_section("PATH")
		l_config_parser.set("PATH", "CNF_FOLDER_PATH", os.path.expanduser("~"))		
		
		l_config_parser.write(file(CNF_CONFIG_FILE, 'w'))

	if "" == CNF_FOLDER_PATH:
		CNF_FOLDER_PATH = os.path.expanduser("~")
	

	log(LOG_VERBOSE, inspect.currentframe().f_lineno, "conf_manager.py::load_configuration()", "CNF_FOLDER_PATH = " + CNF_FOLDER_PATH)
	log(LOG_VERBOSE, inspect.currentframe().f_lineno, "conf_manager.py::load_configuration()", "CNF_PLAYLIST_PATH = " + CNF_PLAYLIST_PATH)
	log(LOG_VERBOSE, inspect.currentframe().f_lineno, "conf_manager.py::load_configuration()", "CNF_SERVER_PATH = " + CNF_SERVER_PATH)
	
	return CNF_FOLDER_PATH
  
def get_server_path():
	return SERVER_PATH

def get_playlist_path():
	return CNF_PLAYLIST_PATH
log(LOG_INFO, inspect.currentframe().f_lineno, "conf_manager.py::load_playlist()")
	l_playlist = []
	try:
		with open(CNF_PLAYLIST_PATH, 'rb') as l_input:
			l_playlist = pickle.load(l_input)
	except:
		log(LOG_WARNING, inspect.currentframe().f_lineno, "conf_manager.py::load_playlist()", "unexisting playlist file: " + CNF_PLAYLIST_PATH)
	
	return l_playlist