# -*- coding: utf-8 -*-
"""
msbase.py -
(c) by Michael Stroeder <michael@stroeder.com>

This module is distributed under the terms of the
GPL (GNU GENERAL PUBLIC LICENSE) Version 2
(see http://www.gnu.org/copyleft/gpl.html)
"""

from collections import defaultdict


def union(a,b,ignorecase=0):
  """
  Return union of two lists a,b.

  If a,b are lists of strings then ignorecase=1 can be used.
  """
  if ignorecase:
    temp = {}
    for elt in a:
      temp[elt.lower()] = elt
    for elt in b:
      temp[elt.lower()] = elt
    return temp.values()
  else:
    raise ValueError,"Senseless to use this function for case-sensitive sets"


class DefaultDict(defaultdict):
  """
  Dictionary which returns a default value for non-existent keys.
  """

  def __init__(self,default=None):
    self.__default__ = default
    defaultdict.__init__(self)

  def __missing__(self,key):
    return self.__default__


class GrabKeys:
  """
  Class for grabbing the string-formatting keys out of a string
  """

  def __init__(self,s):
    self.keys = set([])
    s % self

  def __call__(self):
    return self.keys

  def __getitem__(self, name):
    self.keys.add(name)
    return 0 # 0 is apparently compatible with all % format characters


class CaseinsensitiveStringKeyDict(DefaultDict):
  """
  Dictionary class for case-insensitive string-keyed dictionaries
  """

  def __init__(self,default_dict=None,default=None):
    DefaultDict.__init__(self,default=default)
    self.update(default_dict or {})

  def __setitem__(self,key,value):
    DefaultDict.__setitem__(self,key.lower(),value)

  def __getitem__(self,key):
    return DefaultDict.__getitem__(self,key.lower())


def combinations(l):
  """
  Weird and inefficient implementation of generating all combinations of items in list l
  """
  result = {}
  for i in range(len(l)):
    result[(l[i],)]=None
    for j in range(1,len(l)):
      result[tuple(l[:i])]=None
      result[tuple(l[i:])]=None
  return filter(None,result.keys())


class Unicode1stValueDict(dict):
  charset = 'utf-8'

  def __getitem__(self,key):
    return dict.__getitem__(self,key)[0].decode(self.charset)
