#! /usr/bin/python3

from app import app, db
from app.models.users import Member, Group, GroupPrivilege
from app.models.privs import SpecialPrivilege
import os
import sys
import yaml

help_msg = """
This is the Planète Casio master shell. Type 'exit' or C-D to leave.

Type 'members' to see a list of members and 'groups' to see a list of groups.

Type 'reset-groups-and-privs' to reset all groups and privileges to the
default. This function generates a minimal set of groups and members to prepare
the database.
1. Deletes all groups
2. Creates groups 'Administrateur', 'Modérateur', 'Développeur', 'Rédacteur',
   'Responsable Communauté', 'Partenaire', 'Compte communautaire', 'Robot', and
   'Membre de CreativeCalc'
3. Grants privileges related to these groups
4. Recreates common accounts: 'Planète Casio' (community account) and 'GLaDOS'
   (robot)

Type 'add-group <member> #<group-id>' to add a new member to a group.
"""

def members():
    for m in Member.query.all():
        print(m.name)

def groups():
    for g in Group.query.all():
        print(f"#{g.id}  {g.name}")

def reset_groups_and_privs():
    # Clean up groups
    for g in Group.query.all():
        g.delete()

    # Create base groups
    groups = []
    with open(os.path.join(app.root_path, "data", "groups.yaml")) as fp:
        groups = yaml.load(fp.read())

    for g in groups:
        g["obj"] = Group(g["name"], g["css"], g["descr"])
        db.session.add(g["obj"])
    db.session.commit()

    for g in groups:
        for priv in g.get("privs", "").split():
            db.session.add(GroupPrivilege(g["obj"], priv))
    db.session.commit()

    # Clean up test members
    for name in "PlanèteCasio GLaDOS".split():
        m = Member.query.filter_by(name=name).first()
        if m is not None:
            m.delete()

    # Create template members

    def addgroup(member, group):
        g = Group.query.filter_by(name=group).first()
        if g is not None:
            member.groups.append(g)

    m = Member('PlanèteCasio', 'contact@planet-casio.com', 'v5-forever')
    addgroup(m, "Compte communautaire")
    db.session.add(m)

    m = Member('GLaDOS', 'glados@aperture.science', 'v5-forever')
    m.xp = 1338
    addgroup(m, "Robot")
    db.session.add(m)
    db.session.commit()

    db.session.add(SpecialPrivilege(m, "edit-posts"))
    db.session.add(SpecialPrivilege(m, "shoutbox-ban"))

    db.session.commit()


def add_group(member, group):
    if group[0] != '#':
        print("error: group id should start with '#'.")
        return
    gid = int(group[1:])

    g = Group.query.filter_by(id=gid).first()
    m = Member.query.filter_by(name=member).first()

    m.groups.append(g)
    db.session.add(m)
    db.session.commit()

print(help_msg)

commands = {
    "exit":                     lambda: sys.exit(0),
    "members":                  members,
    "groups":                   groups,
    "reset-groups-and-privs":   reset_groups_and_privs,
    "add-group":                add_group,
}

while True:
    try:
        print('> ', end='')
        cmd = input().split()
    except EOFError:
        sys.exit(0)

    if not cmd: continue
    if cmd[0] not in commands:
        print("error: unknown command.")
    else:
        commands[cmd[0]](*cmd[1:])
