# -*- coding: utf-8 -*-
# ruff: noqa

import threading
import json
from gc import get_objects, garbage
from kivy.clock import Clock
from kivy.cache import Cache
from collections import OrderedDict
from kivy.logger import Logger

try:
    from flask import Flask, render_template_string, make_response
except ImportError:
    Logger.error('WebDebugger: unable to import Flask. Install it!')
    raise

history_max = 250


class MissingOrderedDict(OrderedDict):

    def __missing__(self, key):
        self[key] = [0] * history_max
        return self[key]


metrics = MissingOrderedDict()
app = Flask(__name__)


@app.route('/')
def index():
    return render_template_string(html_index)


@app.route('/metrics.json')
def metrics_json():
    resp = make_response(json.dumps(metrics), 200)
    resp.headers['Content-Type'] = 'text/json'
    return resp


@app.route('/f/<name>')
def getfile(name):
    name = name.replace('.', '_')
    text = globals()[name]
    resp = make_response(text, 200)
    if name.endswith('_js'):
        resp.headers['Content-Type'] = 'text/javascript'
    elif name.endswith('_jpg'):
        resp.headers['Content-Type'] = 'image/jpeg'
    return resp


class FlaskThread(threading.Thread):

    def run(self):
        Clock.schedule_interval(self.dump_metrics, .1)
        app.run(debug=True, use_debugger=True, use_reloader=False)

    def dump_metrics(self, dt):
        m = metrics
        m['Python objects'].append(len(get_objects()))
        m['Python garbage'].append(len(garbage))
        m['FPS (internal)'].append(Clock.get_fps())
        m['FPS (real)'].append(Clock.get_rfps())
        m['Events'].append(len(Clock.get_events()))
        for category in Cache._categories:
            m['Cache ' + category].append(
                len(Cache._objects.get(category, [])))
        for values in m.values():
            values.pop(0)
            values[0] = 0


def start(win, ctx):
    ctx.thread = FlaskThread()
    ctx.thread.daemon = True
    ctx.thread.start()


def stop(win, ctx):
    pass

# -----------------------------------------------------------------------------
# DATA FILES
# -----------------------------------------------------------------------------


html_index = '''
<html>
<head>
<title>Kivy - Web Debugger</title>
<script type='text/javascript' src='/f/jquery.js'></script>
<script type='text/javascript' src='/f/raphael.js'></script>
<script type='text/javascript' src='/f/g_raphael.js'></script>
<script type='text/javascript' src='/f/g_raphael_line.js'></script>
<style type='text/css'>
body {
    font-family: Arial, Helvetica, sans-serif;
    font-size: 13px;
    color: #eee;
    background: url('/f/background.jpg') repeat-x #718693;
}

.panel {
    width: 400px;
    float: left;
    background-color: #BCCAD5;
    margin: 0px 10px 10px 0px;
    padding: 20px;
    -moz-border-radius: 16px;
    -webkit-border-radius: 16px;
    border-radius: 16px;
}

.panel h2 {
    margin: 0px;
    padding: 0px 0px 10px 0px;
    color: #516673;
}

</style>
<script type='text/javascript'>

var graphics = {};
var rid = 0;
var ids = {}

function request_metrics() {
    $.ajax({
    url: '/metrics.json',
    error: function(xhr, status) {
        $('#error').html('Connection lost').show();
        setTimeout('request_metrics()', 1000);
    },
    success: function(data) {
        $('#error').hide();
        for (var key in data) {
            if ( typeof(graphics[key]) == 'undefined' ) {
                rid += 1;
                $('<div class="panel panel' + rid + '"><div id="r' + rid + '"></div></div>').appendTo($('#metrics'));
                $('.panel' + rid).prepend(
                    $('<h2 id="h' + rid + '"></h2>').html(key));
                graphics[key] = Raphael('r' + rid, 400, 150);
                ids[key] = rid;
            }

            var indices = [];
            for (var i = 0; i < data[key].length; i++)
                indices[i] = i;
            var r = graphics[key];
            $('#h'+ids[key]).html(key + ': ' + data[key][i-1]);
            r.clear();
            r.linechart(26, 0, 340, 150, indices, data[key], {
                shade: true, axis: "0 1 0 1" });
        }
        setTimeout('request_metrics()', 250);
    }
    });
}

request_metrics();

</script>
</head>
<body>
<h1>Kivy - Web Debugger</h1>
<div id='error'></div>

<h2>Metrics</h2>
<div id='metrics'>
</div>
</body>
</html>
'''

jquery_js = r'''
/*! jQuery v1.7.1 jquery.com | jquery.org/license */
