'''Command handlers for:

eda pnr --tool=openroad TARGET
'''

from opencos.eda_base import Tool
from opencos.commands.pnr import CommandPnr
from opencos.utils import docker_checks
from opencos.utils.docker_checks import docker_ok

class ToolOpenRoad(Tool):
    '''Tool class for: eda COMMAND --tool=openroad [args] TARGETS'''

    _TOOL= 'openroad'
    _EXE = '' # This is OK to leave empty str, will use config.tools.TOOL.requires-docker
    _URL = 'https://theopenroadproject.org/'

    DEFAULT_DOCKER_IMAGE = "ghcr.io/cognichip/openroad-flow:latest"

    def get_versions(self, **kwargs) -> str:
        if self._VERSION:
            return self._VERSION

        if not docker_ok():
            # docker is required for this tool.
            self.error(f'For --tool={self._TOOL}, you must have functioning "docker"',
                       'see --help for args --docker-run and --docker-image')
            self._VERSION = 'UNKNOWN'
            return self._VERSION

        self.get_set_default_docker_image()

        if not docker_checks.check_image_available(image=self.DEFAULT_DOCKER_IMAGE):
            # Be nice to eda --help, don't call docker run to get versioning if
            # the image hasn't been pulled.
            self._VERSION = 'IMAGE-NOT-PULLED'
            return self._VERSION

        # this is a little customized, b/c we don't really have an Open Road
        # "version", all we have is a git tag or git hash
        git_info_str = (
            'cd /tools/OpenROAD-flow-scripts && echo '
            '$(git log -1 --format=%cs) '
            ### removed checking git tag ### '$(git describe --tags --abbrev=0) '
            '$(git rev-parse --abbrev-ref HEAD) '
            '$(git rev-parse --short HEAD)'
        )
        env_dict = docker_checks.get_docker_env(cmd_des_obj=self)
        version_ret = docker_checks.run_docker_for_version_info(
            image=self.DEFAULT_DOCKER_IMAGE,
            env_dict=env_dict,
            commands=['-c', git_info_str]
        )
        if version_ret:
            self._VERSION = '.'.join(version_ret.strip().split()).replace('..', '.')
        else:
            self._VERSION = 'UNKNOWN'

        return self._VERSION



class CommandPnrOpenRoad(CommandPnr, ToolOpenRoad):
    '''Command handler for: eda pnr --tool=openroad'''

    def __init__(self, config: dict):
        CommandPnr.__init__(self, config=config)
        ToolOpenRoad.__init__(self, config=self.config)

    def do_it(self) -> None:
        self.set_tool_defines()
        self.write_eda_config_and_args()
        self.error('eda pnr --tool=openroad is not supported yet')
