from pathlib import Path

from flask import Blueprint, render_template, url_for, redirect, request
from flask_basicauth import BasicAuth

from . import wandering_monster



class PlayerAuth(BasicAuth):
    def init_app(self, app):
        super().init_app(app)
        self.player_password = app.config['PLAYER_BASIC_AUTH_PASSWORD']

    def check_credentials(self, username, password):
        return (password == self.player_password)

basic_auth = BasicAuth()
player_auth = PlayerAuth()
default_views = Blueprint('default_views', __name__, url_prefix='/')

@default_views.route('/')
def index():
    return render_template('index.html')

@default_views.route('/handbook')
def handbook_index():
    return render_template('handbook.html')

@default_views.route('/handbook/<string:chapter>')
def handbook_section(chapter):
    section_template = 'srd/{}'.format(chapter)
    return render_template(section_template)

@default_views.route('/wiki')
@basic_auth.required
def wiki():
    return render_template('wiki.html')

@default_views.route('/worldmap')
def worldmap():
    return render_template('worldmap.html')

@default_views.route('/lairs')
def lair_gallery():
    base_path = "/srv/www/atr0phy.net/acks/img/dynamic_lairs/"
    base_url = "https://www.atr0phy.net/acks/img/dynamic_lairs/"

    animal_lairs = []
    fs = Path(base_path + "animal/")
    for filename in fs.iterdir():
        animal_lairs.append(base_url + "animal/" + filename.name)

    humanoid_lairs = []
    fs = Path(base_path + "humanoid/")
    for filename in fs.iterdir():
        humanoid_lairs.append(base_url + "humanoid/" + filename.name)

    return render_template('lair_gallery.html', animal=animal_lairs, humanoid=humanoid_lairs)

@default_views.route('/player_tokens')
@player_auth.required
def token_gallery():
    base_path = "/srv/www/atr0phy.net/acks/img/player_tokens/"
    base_url = "https://www.atr0phy.net/acks/img/player_tokens/"

    def to_gallery_src(src):
        return {"src": src, "thumb": src, "subHtml": "<h4>{}</h4>".format(src.rpartition('/')[2])}

    tokens = {}
    parent_fs = Path(base_path)
    for category in parent_fs.iterdir():
        if not category.is_dir():
            continue

        category_fs = Path(base_path + category.name + "/")
        tokens[category.name] = []
        for token in category_fs.iterdir():
            tokens[category.name].append(to_gallery_src(base_url + category.name + "/" + token.name))

    categories = [(k, v) for k, v in tokens.items()]
    categories = sorted(categories, key=lambda category: len(category[1]), reverse=True)
    return render_template('player_tokens.html', categories=categories, data=tokens)

@default_views.route('/wandering_monster')
def view_wandering_monster():
    return render_template('wandering_monster.html')

@default_views.route('/wandering_monster/generate', methods=['POST'])
def generate_wandering_monster():
    data = request.get_json()
    if data['type'] == "dungeon":
        monster = wandering_monster.generate_dungeon_monster(data['check_mod'], data['dungeon_level'], data['reaction_mod'], data['surprise_mod'])
    if data['type'] == "wilderness":
        monster = wandering_monster.generate_wilderness_monster(data['check_mod'], data['terrain_type'], data['reaction_mod'], data['surprise_mod'])
    return monster

@default_views.route('/shares_calculator')
def shares_calculator():
    return render_template('shares_calc.html')
