from zope.interface import implements
from twisted.internet import defer
import formal 
from formal import iformal
from Database import utils as dbutils


REGEX_IP_ADDRESS=('b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).)'
      '{3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)b')

REGEX_EMAIL="^[a-zA-Z0-9]+([\._\-a-zA-Z0-9]+)*@[a-zA-Z0-9]+([._\-a-zA-Z0-9]+[\.][a-zA-Z]{2,5})+$"

REGEX_URI=("(http|https|mail|telnet|ftp|imap|irc|file):\/\/[a-z0-9]+"
   "([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}((:[0-9]{1,5})?\/.*)?$")


class GenericValidator(object):

   def __init__(self, errmsg=u'Cannot validate'):
      self.errmsg = errmsg

   def check(self, value):
      return False

   def validate(self, field, value):
      if not self.check(value):
         raise formal.FieldValidationError(self.errmsg)


class GenericWordListValidator(GenericValidator):

   def __init__(self, wordlist=[], errmsg=u'Word not in list'):
      self.wordlist = wordlist
      GenericValidator.__init__(self, errmsg)

   def check(self, value):
      if value in self.wordlist:
         return True
      else:
         return False


class YesNoValidator(GenericWordListValidator):

   def __init__(self, errmsg=u'Only yes or not are valid values'):
      GenericWordListValidator.__init__(self, ['yes', 'no'], errmsg)


class AcceptPolicy(GenericWordListValidator):
   def __init__(self, errmsg=u'You must accept our terms of usage!'):
      GenericWordListValidator.__init__(self, ['yes'], errmsg)


class EmailExistsValidator(GenericValidator):

   def __init__(self, errmsg=u'This email already exists in our database'):
      GenericValidator.__init__(self, errmsg)

   def check(self, value):
      if dbutils.emailExist(value):
         return False
      return True


class UsernameExistsValidator(GenericValidator):

   def __init__(self, errmsg=u"This username already exists in out database."):
      GenericValidator.__init__(self, errmsg)

   def check(self, value):
      if dbutils.userExists(value):
         return False
      return True


class ValidUsername(GenericValidator):

   def __init__(self, errmsg=u"This username isn't valid, please try another one"):
      GenericValidator.__init__(self, errmsg)

   def check(self, value):
      if value[0] in ['@', '!','>','~']:
         return False
      return True
