from merlin.emerlin import eMerlin
from os import path as os_path
from pickle import load as pickle_load, dump as pickle_dump
import re

def atoi(text):
    return int(text) if text.isdigit() else text
def natural_keys(text):
    return [ atoi(c) for c in re.split('(\d+)',text) ]

class MerlinImage(object):

	getName = 0
	getDescription = 1
	getTags = 2
	getServiceData = 3
	getTimeCreate = 4
	getLength = 5
	getFilesize = 6
	getServiceReference = 7 


	@staticmethod
	def getExtensions():
		return ("avi","divx","mpg","mpeg","mkv","mp4","mov","m4v","wmv","flv")
		
	@staticmethod
	def getAllExtensions():
		return ("avi","divx","mpg","mpeg","mkv","mp4","mov","m4v","wmv","flv","ts")
	
	@staticmethod
	def getMetaData(service, what, allExtensions = False):
		extension = service.getPath().split('.')[-1].lower()
		if (allExtensions == False and extension in MerlinImage.getExtensions()) or (allExtensions == True and extension in MerlinImage.getAllExtensions()):
			metaData = eMerlin.getInstance().parseMeta(service.getPath())
			if metaData:
				if what == MerlinImage.getName:
					return metaData.getName()
				elif what == MerlinImage.getDescription:
					return metaData.getDescription()
				elif what == MerlinImage.getTags:
					return metaData.getTags()
				elif what == MerlinImage.getServiceData:
					return metaData.getServiceData()
				elif what == MerlinImage.getTimeCreate:
					return metaData.getTimeCreate()
				elif what == MerlinImage.getLength:
					return metaData.getLength()
				elif what == MerlinImage.getFilesize:
					return metaData.getFilesize()
				elif what == MerlinImage.getServiceReference:
					return metaData.getServiceReference()
		return None

	@staticmethod
	def imageExtensions(value):
		eMerlin.getInstance().imageExtensions(value)
	

class MerlinFolderSort(object):
	def __init__(self, filename):
		self.filename = filename
		self.dict = self.load()

	def load(self):
		if os_path.exists(self.filename):
			pkl_file = open(self.filename, 'rb')
			if pkl_file:
				folderdict = pickle_load(pkl_file)
				pkl_file.close()
				return folderdict
		return {}

	def save(self):
		pkl_file = open(self.filename, 'wb')
		if pkl_file:
			pickle_dump(self.dict, pkl_file)
			pkl_file.close()	

merlinFolderSort = MerlinFolderSort("/etc/enigma2/merlinfoldersort")

