'''Tool and Command handler for: eda waves --tool=gktwave'''

import os
import subprocess

from opencos.commands.waves import CommandWaves
from opencos.eda_base import Tool
from opencos.files import safe_shutil_which
from opencos.util import debug

class ToolGtkwave(Tool):
    '''Tool GTKWave for viewing waves'''

    _TOOL = 'gtkwave'
    _EXE = 'gtkwave'
    _URL = 'https://gtkwave.sourceforge.net/'

    waveviewer_exe = safe_shutil_which('gtkwave')

    def __init__(self, config: dict):
        super().__init__(config=config)

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

        self._VERSION = ''

        entry = self.config.get('tools', {}).get(self._TOOL, {})
        if not entry:
            return self._VERSION

        if not self.waveviewer_exe:
            return self._VERSION

        # gtkwave --version is fast enough to call subprocess
        proc = None
        try:
            proc = subprocess.run(
                [self.waveviewer_exe, '--version'],
                capture_output=True, check=False
            )
        except Exception as e:
            debug(f'{self.waveviewer_exe} --version: exception {e}')

        if not proc or not proc.stdout:
            return self._VERSION

        for line in proc.stdout.decode('utf-8', errors='replace').split('\n'):
            if line.lower().startswith('gtkwave analyzer v'):
                parts = line.split(' ')
                self._VERSION = parts[2][1:] # trim the leading 'v' in 'v1.2.3'

        return self._VERSION


class CommandWavesGtkwave(CommandWaves, ToolGtkwave):
    '''Handling class for: eda waves --tool=gtkwave'''

    def __init__(self, config: dict):
        CommandWaves.__init__(self, config=config)
        ToolGtkwave.__init__(self, config=self.config)

    def do_it(self) -> None:
        command_list = [
            self.waveviewer_exe, self.wave_file
        ]
        self.exec(os.path.dirname(self.wave_file), command_list)
