# coding=utf-8

import os, json, sys

from flask.json import JSONEncoder
from datetime import date
from speaklater import is_lazy_string

from .staticVariables import DATA_DIR, TEMPLATE_DIR

# http://flask.pocoo.org/snippets/119/
# more useful date format, babel support
class CustomJsonEncoder(JSONEncoder):
	def default(self, object):
		try:
			if isinstance(object, date):
				return object.isoformat()
			iterable = iter(object)
		except TypeError:
			pass
		else:
			return list(iterable)

		# lazy strings support
		if is_lazy_string(object):
			if sys.version_info[0] < 3:
				return unicode(object)
			else:
				return str(object)

		return super(CustomJsonEncoder, self).default(object)

# helper for formatting seconds
def formatSeconds(seconds, signed = True):
	sign = ("+" if (seconds > 0) else "-") if signed else ""
	seconds = abs(seconds)
	m, s = divmod(seconds, 60)
	h, m = divmod(m, 60)
	if h == 0:
		return "%s%02d:%02d" % (sign, m, s)

	return "%s%d:%02d:%02d" % (sign, h, m, s)

# utility for loading json files under data
def loadJson(filename):
	# todo: hardly enough security for file access
	filename = filename.replace('../', '').replace('..\\', '')
	with open(os.path.normpath(os.path.join(DATA_DIR, filename))) as data:
		content = json.load(data)
	return content

# helpers for file lookups
def isDirectory(filename):
	path = os.path.join(TEMPLATE_DIR, filename)
	return not os.path.islink(path) and os.path.isdir(os.path.normpath(path))

def hasTemplate(filename):
	path = os.path.join(TEMPLATE_DIR, filename)
	return not os.path.islink(path) and os.path.isfile(os.path.normpath(path))

def hasData(filename):
	path = os.path.join(DATA_DIR, filename)
	return not os.path.islink(path) and os.path.isfile(os.path.normpath(path))
