#!/usr/bin/env python
# coding: utf-8

"""
    MC6809 - 6809 CPU emulator in Python
    =======================================

    :copyleft: 2014 by the MC6809 team, see AUTHORS for more details.
    :license: GNU GPL v3 or above, see LICENSE for more details.
"""

from __future__ import absolute_import, division, print_function



import atexit
import os
import datetime


DEBUG_FILENAME = os.path.abspath(os.path.join(
    os.path.dirname(__file__),
    "../dragonpy_debug_%s.html" % datetime.datetime.today().strftime("%Y%m%d%H%M%S")
))


HTML_OUT = file(DEBUG_FILENAME, "w")
HTML_OUT.write("""<!DOCTYPE html>
<html><head>
<style>
body {
    font-family:"Lucida Console", Monaco, monospace;
    white-space:nowrap;
}
table, th, td{border-collapse:collapse;border:1px solid black;}
th, td {padding:5px;}
</style>
</head><body><h1>DragonPy Debug:</h1>
<p>created: %s</p>
<table>""" % datetime.datetime.today().isoformat())
print("Create debug file: %s" % DEBUG_FILENAME)


@atexit.register
def close_html_debug():
    HTML_OUT.write("\n</table>\n")
    HTML_OUT.write(
        "<addr>This file was generated by <strong>%s</strong></addr>\n" % (
            os.path.split(__file__)[1]
        )
    )
    HTML_OUT.write("</body></html>")
    HTML_OUT.close()
    print("*** Debug file created:", DEBUG_FILENAME)


CALL_NO = 0
class InstructionHTMLdebug(Instruction):

    def __init__(self, *args, **kwargs):
        super(InstructionHTMLdebug, self).__init__(*args, **kwargs)

    def call_instr_func(self, *args, **kwargs):
        super(InstructionHTMLdebug, self).call_instr_func(*args, **kwargs)

        global CALL_NO
        CALL_NO += 1
        HTML_OUT.write("<tr>\n")
        HTML_OUT.write("<td>%i</td>" % CALL_NO)
        HTML_OUT.write("<td>%x</td>" % self.cpu.last_op_address)
        HTML_OUT.write("<td>%x</td>" % self.opcode)
        HTML_OUT.write("<td>%s</td>" % self.data["mnemonic"])
        HTML_OUT.write("<td>%s</td>" % hex_repr(self.op_kwargs))
        HTML_OUT.write("<td>%s</td>" % self.cpu.get_info)
        HTML_OUT.write("<td>%s</td>" % self.cpu.cc.get_info)
        HTML_OUT.write("<td>%s</td>" % self.cpu.cfg.mem_info.get_shortest(self.cpu.last_op_address))
        HTML_OUT.write("</tr>")
