#!/usr/bin/env python3
""" Listing of source file declarations. """

import sys
import os

from postiats import declarations
from postiats import images
from postiats import locations


def perror(message):
    """ Shorthand to print to `stderr`. """
    print(message, file=sys.stderr)


def error(message):
    """ `perror` and `sys.exit(1)`. """
    perror(message)
    sys.exit(1)


def print_loc(loc):
    """ Shorthand to parse and print formated loc. """
    loc = locations.parse(loc)
    loc = locations.ide_formated(loc)
    print(loc)


HR1 = "========================="
HR2 = "-------------------------"

LABEL1 = "      Name: %s"
LABEL2 = "      Sort: %s"
LABEL3 = "      Type: %s"
LABEL4 = " Sorts are: %s"
LABEL5 = " Construct: %s"


def dump(path):
    """ Dump declarations. """
    print(HR1)
    print(os.path.relpath(path))
    print(HR2)
    first = True
    if declarations.BASE_SORTS:
        print("Base sorts defined or used:")
        for name in sorted(declarations.BASE_SORTS):
            print("   " + name)
            first = False
    if declarations.STATIC_CONSTANTS:
        if not first:
            print(HR2)
        print("Static constants defined or used:")
        for name in sorted(declarations.STATIC_CONSTANTS.keys()):
            sort = declarations.STATIC_CONSTANTS[name]
            print("   " + name + ": " + images.sort_image(sort))
            first = False
    for value in declarations.DECLARATIONS:
        if not first:
            print(HR2)
        first = False
        print_loc(value.loc)
        print(LABEL1 % value.name)
        if value.sort:
            print(LABEL2 % images.sort_image(value.sort))
        if value.type:
            print(LABEL3 % images.type_image(value.type))
            print(LABEL4 % images.type_sorts_image(value.type))
        print(LABEL5 % (" ".join(value.construct)))


def main():
    """ Main. """
    my_name = os.path.split(sys.argv[0])[1]

    recursive = False
    if len(sys.argv) >= 2 and sys.argv[1] == "-r":
        recursive = True
        del sys.argv[1]

    if len(sys.argv) != 2:
        error("Usage: %s [-r] file-name." % my_name)

    path = sys.argv[1]
    declarations.handle_source_file(path)
    dump(path)

    if recursive:
        done = set()
        done.add(path)
        to_be_done = declarations.STALOADED.difference(done)
        while to_be_done:
            path = sorted(to_be_done)[0]
            declarations.handle_source_file(path)
            dump(path)
            done.add(path)
            to_be_done.update(declarations.STALOADED.difference(done))


if __name__ == "__main__":
    main()
