# -*- coding: utf-8 -*-
from dataclasses import dataclass
from typing import Literal


@dataclass
class DColor():

    c_yellow = 226

    # 前景色 (文本颜色)
    red = 31
    green = 32
    yellow = 33
    blue = 34
    magenta = 35  # 洋红
    cyan = 36
    white = 37
    custom = 38
    default = 39

    # 背景色
    bg_black = 40
    bg_red = 41
    bg_green = 42
    bg_yellow = 43
    bg_blue = 44
    bg_magenta = 45
    bg_cyan = 46
    bg_white = 47
    bg_custom = 48
    bg_default = 49

    # 文本样式
    none = 0
    bold = 1
    underline = 4
    reverse = 7

    reset = '\033[0m'

    colors = [
        red,
        green,
        yellow,
        blue,
        magenta,
        cyan,
        white,
        default,
    ]

    bg_colors = [
        bg_black,
        bg_red,
        bg_green,
        bg_yellow,
        bg_blue,
        bg_magenta,
        bg_cyan,
        bg_white,
        bg_default,
    ]

    def text(*args,
             fc: int = None,
             bc: int = None,
             sc: Literal[0, 1, 4, 7] = None):
        _color = DColor.color(fc, bc, sc)
        content = " ".join(args)
        if _color is not None and len(_color) > 0:
            _content = content
            _list = content.split(DColor.reset)
            if len(_list) > 0:
                _sep = DColor.reset + _color
                # _sep = _color
                _content = _sep.join(_list)
            return _color + _content + DColor.reset
        else:
            return content

    def color(fc: int = None,
              bc: int = None,
              sc: Literal[0, 1, 4, 7] = None,
              default=""):
        text = DColor.to_style(sc) + DColor.to_fore_color(
            fc) + DColor.to_back_color(bc)
        if len(text) > 0:
            return text
        else:
            return default

    def to_style(sc: Literal[0, 1, 4, 7] = None):
        if sc in [0, 1, 4, 7]:
            return f"\033[{sc}m"
        else:
            return ""

    def to_fore_color(fc: int = None, ):
        if fc is None or not isinstance(fc, int):
            return ""
        elif fc in DColor.colors:
            return f"\033[{fc}m"
        elif fc >= 0 and fc < 256:
            return f"\033[38;5;{fc}m"
        else:
            return ""

    def to_back_color(bc: int = None, ):
        if bc is None or not isinstance(bc, int):
            return ""
        elif bc in DColor.bg_colors:
            return f"\033[{bc}m"
        elif bc >= 0 and bc < 256:
            return f"\033[48;5;{bc}m"
        else:
            return ""

    def test():
        for i in range(0, 256):
            if i % 10 == 0:
                print()
            print(f'\033[38;5;{i}m' + f'字体颜色{i}' + '\033[0m', end=' ')

    def tips(desc: str):
        return DColor.text(f"{desc}", fc=DColor.white, bc=58, sc=1)
