"""
    Wox session can run multiple tasks within several virtual environments. To help
    the user keep track of what happens in the session, a summary is created at the end
    of each wox session.

    A summary is composed of 4 piece of information:
    - Execution unit: that is the qualification of a task running in a virtual environment;
    - Exit code: 0 if the execution unit succeed or 1 if it fails;
    - Failed at: the action running by the execution unit during the crash;
    - Failure reason: the error message.
"""

from rich.console import Console
from rich.table import Table

from wox.utils import format_duration


def render(wox_session_summary, duration):
    """
        Renders the wox summary from a list of execution units.

        Parameters
        ----------
        wox_session_summary : list[dict]
        duration : float
            Duration in seconds of the wox session.
    """

    console = Console()
    table = Table()
    table.add_column('Execution unit', justify = 'center')
    table.add_column('Exit code', justify = 'center')
    table.add_column('Failed at', justify = 'center')
    table.add_column('Failure reason', justify = 'left')

    for execution_unit in wox_session_summary:
        table.add_row(
            execution_unit['execution_unit'],
            str(execution_unit['exit_code']),
            execution_unit['failed_at'],
            execution_unit['message']
        )

    console.rule(f'Wox session summary ([bold cyan]{format_duration(duration)}[/])')
    console.print(table)

def update_execution_unit_failure(execution_unit, action, exception):
    """
        Updates the execution unit upon failure.

        Parameters
        ----------
        execution_unit : dict
            Execution unit to update.
        action : str
            The last action run by the execution unit before crash.
        exception : Exception
            The exception caught during the crash.
    """

    execution_unit.update({
        'exit_code': 1,
        'failed_at': action,
        'message': str(exception)
    })

def update_execution_unit_success(execution_unit):
    """
        Updates the execution unit upon success.

        Parameters
        ----------
        execution_unit : dict
            Execution unit to update.
    """

    execution_unit.update({
        'exit_code': 0,
        'failed_at': '-',
        'message': '-'
    })
