import os

import requests
from flask import Flask, request, jsonify, make_response

from scraper import TosbaseScraper


app = Flask(__name__)
app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY', 'hackme')
app.config['SLACK_TOKEN'] = os.environ.get('SLACK_TOKEN', None)
app.config['SLACK_WEBHOOK'] = os.environ.get('SLACK_WEBHOOK', None)
app.config['DEBUG'] = True


scraper = TosbaseScraper()


def send_message(channel, user, command, argument, message):
    message['channel'] = "#"+channel

    cmd = "@" + user + " /tos {0} {1}\n".format(command, argument)

    if message.get('attachments'):
        message['attachments'].insert(0, { 'fallback': cmd, 'text': cmd, 'color': '#eeeeee' })
    else:
        message['text'] = cmd + message['text']

    r = requests.post(app.config['SLACK_WEBHOOK'], json=message)


def search_skill_levels(name):
    try:
        skill = scraper.get_skill(name)
    except IndexError:
        return { 'text': 'Unable to find skill with that name.' }

    level_fields = []
    for level in skill['levels']:
        level_fields.append({
            'title': 'Level ' + level['level'],
            'value': level['description'] + '\n' + 'CD: ' + level['cd'] + '\n' + 'SP: ' + level['sp'] + '\n',
            'short': True
        })

    attachments = []
    attachments.append({
        'fallback': skill['url'],
        'color': '#439FE0',
        'title': '{0} Skill Levels'.format(skill['name']),
        'title_link': skill['url'],
        'fields': level_fields,
        "thumb_url": skill['image'],
    })

    message = {
        'username': 'Skill Info',
        'icon_url': 'http://www.tosbase.com/content/img/classes/class_cataphract_f.gif',
        'attachments': attachments
    }

    return message

def search_skill(name):
    try:
        skill = scraper.get_skill(name)
    except IndexError:
        return { 'text': 'Unable to find skill with that name.', }

    attachments = []
    attachments.append({
        'fallback': skill['name'],
        'color': '#439FE0',
        'title': skill['name'],
        'title_link': skill['url'],
        'fields': [
            {
                'title': 'Description',
                'value': skill['description'],
                'short': False
            },
            {
                'title': 'Class',
                'value': skill['class'],
                'short': True
            },
            {
                'title': 'Circle',
                'value': skill['circle'],
                'short': True
            },
            {
                'title': 'Type',
                'value': skill['type'],
                'short': True
            },
            {
                'title': 'Cooldown',
                'value': skill['cd'],
                'short': True
            },
            {
                'title': 'SP Cost',
                'value': skill['sp'],
                'short': True
            },
            {
                'title': 'Stance',
                'value': skill['stance'],
                'short': True
            },
            {
                'title': 'Video',
                'value': '<' + skill['video'] + '|Link>',
                'short': True
            }
        ],
        'thumb_url': skill['image'],
        'mrkdown': True
    })

    level_fields = []
    for i, level in enumerate(skill['levels']):
        if i+1 == 1 or (i+1) % 5 == 0:
            level_fields.append({
                'title': 'Level ' + level['level'],
                'value': level['description'] + '\n' + 'CD: ' + level['cd'] + '\n' + 'SP: ' + level['sp'] + '\n',
                'short': True
            })

    attachments.append({
        "fallback": skill['url'],
        "color": "#439FE0",
        "title": "{0} Skill Levels".format(skill['name']),
        "fields": level_fields
    })

    message = {
        'username': 'Skill Info',
        'icon_url': 'http://www.tosbase.com/content/img/classes/class_cataphract_f.gif',
        'attachments': attachments
    }

    return message


def search_mob(name):
    try:
        mob = scraper.get_mob(name)
    except IndexError:
        return { 'text': 'Unable to find a mob with that name.', }

    attachments = []
    attachments.append({
        "fallback": mob['name'],
        "color": "#439FE0",
        "title": mob['name'],
        "title_link": mob['url'],
        "fields": [
            {
                "title": "Level",
                "value": mob['level'],
                "short": True
            },
            {
                "title":
                "Type", "value":
                mob['type'], "short": True
            },
            {
                "title": "HP",
                "value": mob['hp'],
                "short": True
            },
            {
                "title": "Base XP",
                "value": mob['base_exp'],
                "short": True
            },
            {
                "title": "Class XP",
                "value": mob['class_exp'],
                "short": True
            },
            {
                "title": "Element",
                "value": mob['element'],
                "short": True
            },
        ],
        "thumb_url": mob['image'],
        "mrkdwn": True
    })

    message = {
        "username": "Mob Info",
        "icon_url": "http://www.tosbase.com/content/img/classes/class_cataphract_f.gif",
        'attachments': attachments
    }

    return message


@app.route('/commands/search', methods=['POST'])
def search():
    token = request.form['token']
    if token != app.config['SLACK_TOKEN']:
        return "Invalid Request"

    channel = request.form['channel_name']
    channel_id = request.form['channel_id']
    text = request.form['text']

    user = request.form['user_name']

    commands = ['mob', 'skill', 'slvl']
    command = text.split(" ")[0]
    argument = " ".join(text.split(" ")[1:])

    if command not in commands:
        return "Can not look up {0}. Supported searches: {1}".format(command, ", ".join(commands))

    if command == 'mob':
        send_message(channel, user, command, argument, search_mob(argument))

    if command == 'skill':
        send_message(channel, user, command, argument, search_skill(argument))

    if command == 'slvl':
        send_message(channel, user, command, argument, search_skill_levels(argument))

    return ('', 204)
