#!/usr/bin/env python3
# -*- coding: utf-8 -*-


import argparse
import logging
import os

from rich_argparse import RichHelpFormatter

from idstools.machinedescription import get_md_data
from idstools.utils.clihelper import show_plot, rcparam_parser
from idstools.utils.idslogger import setup_logger
from idstools.view.common import PlotCanvas
from idstools.view.domain.mdplot import plot_machine_description

# ----------------------------------------------------------------------


logger = setup_logger("module", stdout_level=logging.INFO)


if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description="---- View and plot machine description with one or more URIs as data entries",
        formatter_class=RichHelpFormatter,
        parents=[
            rcparam_parser,
        ],
    )
    parser.add_argument(
        "-u",
        "--uri",
        nargs="*",
        default=[],
        help="""Provide machine descriptions that you need to plot\n
    with uris for example\n
    "imas:mdsplus?user=public;pulse=116000;run=4;database=ITER_MD;version=3#wall",
    "imas:mdsplus?user=public;pulse=116000;run=4;database=ITER_MD#wall:0/description2d[0]/vessel/unit[:]",
    "imas:mdsplus?user=public;pulse=116000;run=4;database=ITER_MD;version=3",
    "imas:hdf5?path=./testdb",
    "testpulse.nc"
    """,
    )
    parser.add_argument(
        "--dd-update",
        action="store_true",
        help=(
            "Convert IDS to the default version of the data dictionary if enabled"
            "otherwise, use the original IDS stored on disk."
        ),
    )
    parser.add_argument(
        "--save",
        help=(
            "Save the plot to a file instead of opening a window. "
            "If no plot window is available, it is saved automatically."
        ),
        action="store_true",
    )
    parser.add_argument(
        "--directory",
        help="Directory to save the figure",
        default=None,
    )
    args = parser.parse_args()

    ids_data = get_md_data(args.uri, args.dd_update)

    # Initialization
    mdcanvas = PlotCanvas(1, 1, figsize=(10, 10))
    mdcanvas.update_style(args.rc)
    ax = mdcanvas.add_axes(title="", xlabel="R (m)", ylabel="Z (m)", row=0, col=0)
    md_provenance = plot_machine_description(ax, ids_data)
    ax.set_title("")
    mdcanvas.fig.subplots_adjust(top=0.916, bottom=0.09, left=0.044, right=0.953, hspace=0.287, wspace=0.2)
    mdcanvas.get_current_fig_manager().set_window_title(os.path.basename(__file__))
    mdcanvas.set_sup_title("" if args.no_provenance else md_provenance, fontsize=8)
    show_plot(mdcanvas, args, fname=os.path.basename(__file__) + "_machine_description.png")
