#!/usr/bin/env python
# -*- encoding=utf8 -*-

"""
Author: Hanyu Wang
Created time: 2023-03-09 16:39:58
Last Modified by: Hanyu Wang
Last Modified time: 2023-03-19 00:41:28
"""

from xyz.network import Network


def write_blif_to_string(ntk: Network) -> str:
    """
    write the blif to a string
    """

    blif_string = "# Generated by MADBuf\n"

    if ntk.get_name() is None or ntk.get_name() == "":
        ntk.set_name("unknown")

    blif_string += ".model " + ntk.get_name() + "\n"

    blif_string += ".inputs "

    for input_name in ntk.pis():
        blif_string += input_name + " "

    blif_string += "\n"

    blif_string += ".outputs "

    for output in ntk.pos():
        blif_string += output + " "

    blif_string += "\n"

    for register_output, register_input in ntk.ro_to_ris().items():
        blif_string += ".latch\t" + register_input + " " + register_output + " 2\n"

    for node in ntk.constant0s():
        blif_string += ".names\t" + node + "\n0\n"

    for node in ntk.constant1s():
        blif_string += ".names\t" + node + "\n1\n"

    for node in ntk.get_nodes():
        blif_string += ".names\t"

        for fanin in ntk.fanins(node):
            blif_string += fanin + " "

        blif_string += node + "\n"

        for truth_table in ntk.get_func(node):
            blif_string += truth_table + "\n"

    blif_string += ".end\n"

    return blif_string


def write_blif(ntk: Network, filename: str):
    """
    write the blif to a file
        TODO:
            - consider also the blackboxes
    """

    file = open(filename, "w", encoding="utf-8")
    file.write(write_blif_to_string(ntk))
    file.close()
