# -*- coding: utf-8 -*-
"""KiBlast KiCad BOM Generator and Costing

This BOM plugin for kicad generates a spreadsheet or csv of the Bill
of materials of a board.  It attempts to cost said BOM from Octopart
or known local prices.  It also picks from known stock and includes
the local stocking price.

Todo:
    * Everything

SPDX-License-Identifier: GPL-3.0-or-later
Copyright © 2019 Steven Johnson
"""
from .defs import defs
from .config import KiBlastConfig
from .eeschema_xml import eeschema_xml
from .datafiles import DataTableFile, AllData

import click
import os
import appdirs

CACHE_DIR = appdirs.user_cache_dir(defs.APPNAME, defs.APPAUTHOR)
LOG_DIR = appdirs.user_log_dir(defs.APPNAME, defs.APPAUTHOR)


@click.group(context_settings=dict(help_option_names=["-h", "--help"]))
@click.version_option(version=defs.SHORTVERSION)
def main():
    pass


@main.command()
@click.argument("infile", type=click.File("rb"))
@click.argument("outfile", type=click.Path(dir_okay=False))
@click.option("--nostock", is_flag=True, help="Dont use parts in stock")
@click.option("--nooctopart", is_flag=True, help="Dont cost parts on octopart")
def bom(infile, outfile, nostock, nooctopart):
    """ Generate a BOM from the XML Data exported by KiCad.

    INFILE  the Name of the XML Schematic Data file generated by KiCad.
    OUTFILE the Name of the generated BOM File.

    \b
            OUTFILE with extension
                .csv is generated as a text CSV file.
                .xlsx is generated as Microsoft Excel spreadsheet.
                Anything else is an error.
    """

    # Get active configuration
    cfg = KiBlastConfig()

    # Command line processor already checked and opened infile for us.

    # Check we know the output file type, and exit if we don't.
    output_type = os.path.splitext(outfile)[1]
    if output_type not in [".csv", ".xlsx"]:
        print(
            "Output File Type '{}' is Unknown.  Use '.csv' or '.xlsx'. Aborted!!".format(
                output_type
            )
        )
        exit(2)

    # OK, so start processing the BOM.
    data = AllData()


@main.command()
def dump_Extra_Parts(**kwargs):
    """ Show all the extra parts which will be included in the BOM. """
    data = AllData()
    data.extras.dumpAllData()


@main.command()
@click.argument("infile", type=click.File("rb"))
def dump_bom(infile):
    """ Show all the data from the kicad exported BOM.

    INFILE   the Name of the XML Schematic Data file generated by KiCad.
    """
    # Get active configuration
    cfg = KiBlastConfig()

    eexml = eeschema_xml(infile, cfg)
    print("BOARD TITLE: {}".format(eexml.BoardTitle()))
    print("COMPANY    : {}".format(eexml.Company()))
    print("REVISION   : {}".format(eexml.BoardRev()))
    print("DATE       : {}".format(eexml.BoardDate()))
    print("EXPORTED   : {}".format(eexml.ExportDate()))
    print("REF, VALUE, SIZE, FOOTPRINT, VARIANT, MFG, MPN, EQUIVOK, FITTED")
    for ref in eexml.get_all_refs():
        comps = eexml.get_component(ref)
        for comp in comps:
            for variant in comp["PARTS"].keys():
                print(
                    "{}, {}, {}, {}, {}, {}, {}, {}, {}".format(
                        comp["REF"],
                        comp["VALUE"],
                        comp["SIZE"],
                        comp["FOOTPRINT"],
                        str(variant),
                        comp["PARTS"][variant]["MFG"],
                        comp["PARTS"][variant]["MPN"],
                        str(comp["PARTS"][variant]["EQUIVOK"]),
                        str(comp["PARTS"][variant]["FITTED"]),
                    )
                )


@main.command()
def paths(**kwargs):
    """ Show file search paths. """
    print(defs.FULLVERSION)
    print()
    print("Configuration Files will be searched:")
    for cfgfile in KiBlastConfig.CFG_NAMES:
        print("    {:8} : {}".format(cfgfile[1], cfgfile[0]))
    print()

    print("Directories where Data Files will be searched:")
    for dir in DataTableFile.DATA_DIRS:
        print("    " + dir)
    print()

    print("Directory where Cached Data will be stored:")
    print("    " + CACHE_DIR)
    print()

    print("Directory where Logs will be stored:")
    print("    " + LOG_DIR)
    pass


@main.command()
@click.option(
    "--dark", "color", flag_value=0, default=True, help="Color output for Dark Terminal"
)
@click.option("--light", "color", flag_value=1, help="Color output for Light Terminal")
@click.option("--raw", "color", flag_value=2, help="No Color to terminal")
@click.option("--defaults", flag_value=True, default=False, help="Only Show Defaults")
def config(color, defaults):
    """ Show the active configuration. """
    cfg = KiBlastConfig(default_only=defaults)
    cfg.dump(color)


if __name__ == "__main__":
    main()
