from . import logutil
import json
import bottle
import logging
from bottle import Jinja2Template, jinja2_view, static_file, response, Bottle, request
import functools
from cheroot import wsgi
import os
# this is somehow easier than actually using sockets..
import sh

logger = logging.Logger('tsmon')

QUERY_SOCKET = "/tmp/ts-squery.sock"

def get_stati():
    try:
        result = sh.nc('-U', QUERY_SOCKET, _in='status')
    except sh.ErrorReturnCode:
        return []
    return json.loads(result.stdout.decode('utf-8'))

Jinja2Template.settings = {'autoescape': True}
view = functools.partial(jinja2_view, template_lookup=["templates"])

app = Bottle()
app.config['TEMPLATES_AUTO_RELOAD'] = True

@app.hook('after_request')
def enable_cors():
    """
    You need to add some headers to each request.
    Don't use the wildcard '*' for Access-Control-Allow-Origin in production.
    """
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'PUT, GET, POST, DELETE, OPTIONS'
    response.headers['Access-Control-Allow-Headers'] = 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'

@app.route('/poke', method='POST')
def poke():
    clid = request.body.read().decode('utf-8')
    sh.nc('-U', QUERY_SOCKET, _in=f'poke {clid}')

def get_ts_data():
    logfile = logutil.find_last_log('/opt/teamspeak')
    log_edited = []
    with open(logfile) as f:
        for line in f:
            parts = line.split('|')
            log_edited.append(f"{parts[0]} {parts[4]}")

    stati = get_stati()
    keys = ('clid', 'client_nickname', 'client_idle_time', 'client_output_muted', 'client_input_muted')
    online_data = [[status[key].replace(r'\s', ' ') for key in keys] for status in stati if 'serveradmin' not in status['client_nickname']]

    return online_data, log_edited[::-1]

@app.route('/')
@view('index.html')
def online():
    online_data, log_edited = get_ts_data()
    return {"user_data": online_data,
            "full_log": log_edited}

@app.route('/json_with_log')
def jsonline2():
    online_data, log_edited = get_ts_data()
    if online_data:
        online_users, out_muted, in_muted = zip(*[(d[1], d[3]=="1", d[4]=="1") for d in online_data])
    else:
        online_users, out_muted, in_muted = ([], [], [])
    return json.dumps({"people": online_users, "input_muted": in_muted, "output_muted": out_muted, "log": log_edited})


@app.route('/json')
def jsonline():
    online_data, log_edited = get_ts_data()
    if online_data:
        online_users, out_muted, in_muted = zip(*[(d[1], d[3]=="1", d[4]=="1") for d in online_data])
    else:
        online_users, out_muted, in_muted = ([], [], [])
    return json.dumps({"people": online_users, "input_muted": in_muted, "output_muted": out_muted})

@app.route('/static/:path#.+#', name='static')
def static(path):
    return static_file(path, root='static')
