# Copyright (c) 2024 Sijmen Woutersen
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import datetime

class Trace:
    def __init__(self, vcd_file, trace_all=False, **pins):
        self.pins = pins
        self.trace_all = trace_all
        self.t = 0
        self.ids = {}
        self.f = open(vcd_file, "wt")
        self.f.write(f"$version Generated by ebyst $end\n")
        self.f.write(f"$date {datetime.datetime.now()} $end\n")
        self.f.write(f"$timescale 1ps $end\n")
        self.f.write(f"$scope module TOP $end\n")
        for i, name in enumerate(pins):
            if isinstance(pins[name], list) or (isinstance(pins[name], tuple) and trace_all):
                n = len(pins[name])
            else:
                n = 1
            self.ids[name] = chr(i+65)
            self.f.write(f"$var wire {n} {chr(i+65)} {name} $end\n")
        self.f.write(f"$upscope $end\n")

    def __del__(self):
        self.f.close()

    def snapshot(self):
        self.f.write(f"#{self.t}\n")
        for name, pin in self.pins.items():
            if isinstance(pin, list) or (isinstance(pin, tuple) and self.trace_all):
                s = ""
                for pin in pin:
                    v = pin.get_value()
                    if v is None: v = 'X'
                    s = str(v) + s
                self.f.write(f"b{s} {self.ids[name]}\n")
            else:
                v = pin.get_value()
                if v is None: v = 'X'
                self.f.write(f"{v}{self.ids[name]}\n")
        self.t += 1