import typing
from typing import Dict


def add_paystub(f: typing.IO,
                earnings: float,
                pretax_vals: Dict,
                *,
                scale: float = 2,
                use_percent: bool = False) -> int:
    """Create SankeyMatic strings from configuration income+pretax info

    Args:
        f: output file
        earnings: net income
        pretax_vals: dictionary with all pretax items and their value
        scale: scaling factor to apply to all values (based on time period)
        use_percent: use percentages or absolute vals

        The format is:
            {Source} [{Amount}] {Type}

        Returns:
            total take home income over the plotting period
    """
    take_home = earnings * scale
    if use_percent:
        f.write(f'Spending [{int(100)}] Wages\n')
    else:
        f.write(f'Spending [{int(take_home)}] Wages\n')

    sorted_pretax = sorted(pretax_vals.items(), key=lambda kv: kv[1])
    sorted_pretax.reverse()
    for name, value in sorted_pretax:
        if use_percent:
            f.write(f'Wages [{int(100 * value / earnings)}] {name}\n')
        else:
            f.write(f'Wages [{int(value * scale)}] {name}\n')

        take_home -= value * scale

    if use_percent:
        val = int(100 * take_home / earnings / scale)
    else:
        val = int(take_home)
    f.write(f'Wages [{val}] Total Income\n')

    return int(take_home)