#!/usr/bin/env python

# This file is part of Window-Switch.
# Copyright (c) 2009-2013 Antoine Martin <antoine@nagafix.co.uk>
# Window-Switch is released under the terms of the GNU GPL v3

import base64
import binascii

from winswitch.util.simple_logger import Logger
from winswitch.util.common import visible_command, no_newlines, csv_list
from winswitch.consts import BASE64, BINASCII

logger=Logger("format_util", log_colour=Logger.MAGENTA)


BASE64_PREFIX = "base64:"

def binencode(data, binary_encodings=[BINASCII]):
	if BASE64 in binary_encodings:
		return	BASE64_PREFIX + base64.b64encode(data)
	return	binascii.hexlify(data)

def bindecode(data):
	if not data:
		return	data
	s = str(data)
	if s.startswith(BASE64_PREFIX):
		return	base64.b64decode(s[len(BASE64_PREFIX):])
	return	binascii.unhexlify(s)


def format_message(command, params=None, encrypted_commands=[], do_encrypt=False, key=None, salt=None):
	if params and len(params)>0:
		p_str = None
		for param in params:
			if param is None:
				param = ""
			if type(param)==dict:
				f = opts_format(param)
			elif type(param)==list:
				f = list_format(param)
			else:
				f = str(param)
			if not p_str:
				p_str = "'" + f
			else:
				p_str += "','" + f
		p_str += "'"
		if command:
			message = "%s %s" % (command, p_str)
		else:
			message = p_str
	else:
		message = command
	return	message

def list_format(_list):
	return	csv_list(_list)

def opts_format(_dict):
	s = ""
	if _dict:
		for k,v in _dict.items():
			s += "%s=%s;" % (k,v)
	return s

def parse_message_string(command):
	if not command:
		return (None, None)
	def logerr(msg):
		cmd_out = visible_command(command)
		sig = "(%s)" % cmd_out
		logger.error(sig+msg)
	try:
		split = no_newlines(command).split(" ", 1)
		cmd = split[0]
		if len(split) == 1:
			args = []
		elif len(split) == 2:
			args_csv = split[1]
			l = len(args_csv)
			if l<2 or args_csv[0]!="'" or args_csv[l-1]!="'":
				logerr("arguments are missing quotes")
				return (None, None)
			args_csv = args_csv[1:l-1]
			args = args_csv.split("','")
		else:
			logerr("unknown command format, found %d parts instead of 1 or 2" % len(split))
			return (None,None)
		return	(cmd, args)
	except Exception, e:
		logerr(str(e))
		return (None,None)
