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

##
## utilitylib.py
##  - Miscellanoues tiny and trivial but nevertheless useful utility
##    functions used by It'sGotTheVibez, an offline last.fm scrobbler
##    for Trekstor's "Vibez" portable music player.
## See http://www.ohrner.net/ for latest news and updates, please.
## 
## Copyright (C) 2007-2008 Gunter Ohrner "gunter _(@)_ ohrner.net"
##
## 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
##

import os
import time

##
## Utility Functions
##


def safeClose(file_obj):
	"""Safely close a file(-like) object."""
	if file_obj != None:
		try:
			file_obj.close()
		except:
			pass



def xint(value, default = 0):
	'''Casts the first argument "value" to an integer and returns it.
	In case the cast fails, the second argument is returned, which
	defaults to the integer "0" (zero).'''
	
	try:
		return int(value)
	except:
	 	## value was invalid
		return int(default)



def emptyIfNone(value, dfl = ''):
	'''If the first argument "value" is not "None",, it is returned.
	Otherwise, the second argument is returned, which defaults to
	the empty string.'''
	
	if value == None:
		return dfl
	else:
		return value



def noneIfEmpty(value, dfl = None):
	'''Converts its first argument "value" to a string and strips() it.
	If the result is a non-emtpy string, it is returned, otherwise the
	second argument is returned, which defaults to "None"'''
	
	strvalue = str(value).strip()
	if strvalue == '':
		return dfl
	else:
		return strvalue



def flattenListOfLists(list_of_lists):
	'''Merges all elements from a list of lists into a single list.
	ie. [[a, b], [], [c, d, e], [f]] becomes [a, b, c, d, e, f]'''
	result = []
	for lst in list_of_lists:
		result += lst

	return result



def getFirst(*args):
	'''Returns the first argument which is not "None", comparable to the
	SQL function COALESCE(). Returns "None" if and only if no non-"None"
	argument was provided.'''
	
	for arg in args:
		if arg != None:
			return arg

	return None



def formatTS(ts):
	'''Converts a UNIX timestamp in UTC to a readable representation.'''
	
	return time.strftime('%Y-%m-%d %H-%M-%S',
											 time.gmtime(ts))



class LessThanLimitPredicate( object ):
	'''Unary predicate which ignores its argument,
	returns "limit" times True, and only False afterwards.'''

	def __init__(self, limit):
		self.limit = limit
		self.call_counter = 0

	def __call__(self, dummy):
		self.call_counter += 1
		return self.call_counter <= self.limit
