from collections import OrderedDict
import importlib
import inspect


class MessageBase:
    _type = None

    def __init__(self, ordered_args):
        super().__init__()
        self._fields = ordered_args.keys()
        self._asdict = ordered_args

    def __str__(self):
        result_string = ' '.join(['{type}',
                                  ''.join(['{{{f}}}'.format(f=field)
                                           if self._asdict[field].endswith(":")
                                           else '{{{f}}} '.format(f=field)
                                           for field in self._fields
                                           if self._asdict[field]])])

        return ''.join([result_string.rstrip().format(type=self.type(),
                                                      **self._asdict),
                        '\r\n'])

    @classmethod
    def type(cls):
        return cls._type if cls._type \
            else cls.__name__.upper().replace('MESSAGE', '')

    def __getattr__(self, attr):
        return getattr(str(self), attr)

    @classmethod
    def from_str(cls, string):
        prefix = ''
        trailing = []
        if not string:
            raise Exception("Empty line.")
        if string[0] == ':':
            prefix, string = string[1:].split(' ', 1)
        if string.find(' :') != -1:
            string, trailing = string.split(' :', 1)
            args = string.split()
            args.append(trailing)
        else:
            args = string.split()
        command = args.pop(0)
        module = importlib.import_module(__name__)
        try:
            class_ = getattr(module, '{command}Message'.
            format(command=command.capitalize()))
            del module
            print("CREATING {} with args {}".format(class_, args))
            msg = class_(*args)
            return (msg)
        except AttributeError:
            pass
        return None


        #return prefix, command, args


class ParameterizedMessage(MessageBase):
    def __init__(self, prefix=None, infix=None, suffix=None):
        frame = inspect.currentframe()
        args, _, _, kwargs = inspect.getargvalues(frame)
        del frame
        ordered_args = OrderedDict(((arg, kwargs[arg]) for arg in args[1:]))
        super().__init__(ordered_args)


class ModeMessageBase(ParameterizedMessage):
    _type = 'MODE'

    def __init__(self, channel=None, mode=None, user=None):
        if mode is None:
            mode = self._mode
        super().__init__(channel, mode, user)


class ModeMessage(ModeMessageBase):
    _mode = None

    def __init__(self, channel=None, user=None):
        super().__init__(channel=channel, user=user)


class BanMessage(ModeMessage):
    _mode = '+b'


class UserMessage(ParameterizedMessage):
    _infix = '0 * :'

    def __init__(self, nick=None, name=None):
        super().__init__(nick, self._infix, name)


class QuitMessage(ParameterizedMessage):
    _infix = ':'
    _message = "Good bye my friend it's hard to die!"

    def __init__(self, message=None):
        if message is None:
            message = self._message
        super().__init__(infix=self._infix, suffix=message)


class SimpleMessage(ParameterizedMessage):
    def __init__(self, param=None):
        super().__init__(param)


class NickMessage(SimpleMessage):
    pass


class JoinMessage(SimpleMessage):
    pass


class PartMessage(SimpleMessage):
    pass


class PingMessage(SimpleMessage):
    pass


class PongMessage(SimpleMessage):
    def __init__(self, msg):
        sender = msg.split()[1]
        super().__init__(sender)

@@ -50,23 +50,8 @@
 lib%0A
-import inspect%0A
 %0A%0Acl
@@ -75,32 +75,50 @@
     _type = None
+%0A    prefix = None
 %0A%0A    def __init
@@ -1835,16 +1835,48 @@
 (*args)%0A
+            msg.prefix = prefix%0A
         
@@ -1966,48 +1966,8 @@
 e%0A%0A%0A
-        #return prefix, command, args%0A%0A%0A
 clas
@@ -2030,55 +2030,31 @@
 lf, 
-prefix=None, infix=None, suffix=None
+*parameters
 ):%0A
+%0A
         
 fram
@@ -2053,36 +2053,71 @@
     
-f
+pa
 rame
- = inspect.currentframe
+ters = list(parameters)%0A        trailing = parameters.pop
 ()%0A 
@@ -2127,151 +2127,408 @@
     
+p
 ar
-gs, _, _, kwargs = inspect.getargvalues(frame)%0A        del frame%0A        ordered_args = OrderedDict(((arg, kwargs%5Barg%5D) for arg in args%5B1:%5D))
+ameters = %5Bstr(param) for param in parameters%0A                      if param is not None%5D%0A%0A        if len(parameters) %3E 0:%0A            parameters = %22 %22.join(parameters)%0A            if trailing is not None:%0A                trailing = ':%7Btrailing%7D'.format(trailing=trailing)%0A        ordered_args = OrderedDict()%0A        ordered_args%5B'middle'%5D = parameters%0A        ordered_args%5B'trailing'%5D = trailing
 %0A   
@@ -2785,24 +2785,30 @@
 , mode, user
+, None
 )%0A%0A%0Aclass Mo
@@ -3052,30 +3052,8 @@
 e):%0A
-    _infix = '0 * :'%0A%0A
     
@@ -3087,24 +3087,32 @@
 e, name=None
+, mode=0
 ):%0A        s
@@ -3133,27 +3133,25 @@
 _(nick, 
-self._infix
+mode, '*'
 , name)%0A
@@ -3197,25 +3197,8 @@
 e):%0A
-    _infix = ':'%0A
     
@@ -3379,34 +3379,12 @@
 t__(
-infix=self._infix, suffix=
+'', 
 mess
@@ -3456,21 +3456,24 @@
 _(self, 
-param
+trailing
 =None):%0A
@@ -3497,21 +3497,24 @@
 _init__(
-param
+trailing
 )%0A%0A%0Aclas

Restructure messages.