from flask import Flask
from flask.ext.restful import reqparse, abort, Api, Resource

import sys
import os.path
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)))

from helpers.log import logging
from helpers.settings import config
import helpers.amq

app = Flask(__name__)
api = Api(app)

parser = reqparse.RequestParser()

parser.add_argument('protocol', type=str, required=False)
parser.add_argument('user', type=str, required=True)
parser.add_argument('channel', type=str, required=True)
parser.add_argument('message', type=str, required=True)

class Push(Resource) :

    def post(self) :
        args = parser.parse_args()
        message     = args['message']
        channel     = args['channel']
        username    = args['user']
        protocol    = args['protocol']
        helpers.amq.push(message=message,channel=channel,username=username,protocol=protocol)
        return {'success' : True}

class Message(Resource) :

    def post(self) :
        args = parser.parse_args()
        if args['message'][0:1] == '!' :
            command = args['message'].split(' ')[0][1:]
            try :
                mod_str = 'plugins.%s' % command
                mod = __import__(mod_str)
                attr = getattr(mod, command)
                attr.main(args)
            except :
                msg = "'%s' module does not exist" % command
                helpers.amq.push(message=msg,channel=config['irc']['channel'],username=config['irc']['uname'])
                return {'success' : False}
                
        return {'success' : True}

api.add_resource(Message, '/privmsg')
api.add_resource(Push, '/push')

if __name__ == '__main__' :
    app.run(
        host    = config['api']['host'], 
        debug   = config['api']['debug'],
        port    = int(config['api']['port'])
    )
