from typing import NamedTuple

from kitty.fast_data_types import Color, Screen
from kitty.tab_bar import DrawData, ExtraData, TabBarData, as_rgb, draw_title


class TabColors(NamedTuple):
    active_fg: Color
    active_bg: Color
    inactive_fg: Color
    inactive_bg: Color


TAB_ACCENT = Color(0x2e, 0x84, 0xe6)


def tab_colors(theme_bg: Color) -> TabColors:
    return TabColors(theme_bg, TAB_ACCENT, TAB_ACCENT, theme_bg)


def draw_tab(
    draw_data: DrawData, screen: Screen, tab: TabBarData,
    before: int, max_title_length: int, index: int, is_last: bool,
    extra_data: ExtraData
) -> int:
    colors = tab_colors(draw_data.default_bg)
    fg = colors.active_fg if tab.is_active else colors.inactive_fg
    bg = colors.active_bg if tab.is_active else colors.inactive_bg
    default_bg = as_rgb(int(draw_data.default_bg))
    orig_fg = as_rgb(int(fg))
    orig_bg = as_rgb(int(bg))
    title_draw_data = draw_data._replace(**colors._asdict())
    screen.cursor.fg = orig_fg
    screen.cursor.bg = orig_bg
    left_sep, right_sep = ('', '')

    def draw_sep(which: str) -> None:
        screen.cursor.bg = default_bg
        screen.cursor.fg = orig_bg
        screen.draw(which)
        screen.cursor.bg = orig_bg
        screen.cursor.fg = orig_fg

    if max_title_length <= 1:
        screen.draw('…')
    elif max_title_length == 2:
        screen.draw('…|')
    elif max_title_length < 6:
        draw_sep(left_sep)
        screen.draw((' ' if max_title_length == 5 else '') + '…' + (' ' if max_title_length >= 4 else ''))
        draw_sep(right_sep)
    else:
        draw_sep(left_sep)
        screen.draw(' ')
        draw_title(title_draw_data, screen, tab, index)
        extra = screen.cursor.x - before - max_title_length
        # print("extra:%d" %(extra))
        if extra >= 0:
            screen.cursor.x -= extra + 3
            screen.draw('…')
        elif extra == -1:
            screen.cursor.x -= 2
            screen.draw('…')
        screen.draw(' ')
        draw_sep(right_sep)
        draw_sep(' ')

    screen.cursor.bg = default_bg
    screen.cursor.fg = orig_fg
    return screen.cursor.x
