-module(utils). -compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). -export([get_ansi_code/1]). -spec hex_value(binary()) -> {ok, integer()} | {error, nil}. hex_value(Value) -> case Value of <<"0"/utf8>> -> {ok, 0}; <<"1"/utf8>> -> {ok, 1}; <<"2"/utf8>> -> {ok, 2}; <<"3"/utf8>> -> {ok, 3}; <<"4"/utf8>> -> {ok, 4}; <<"5"/utf8>> -> {ok, 5}; <<"6"/utf8>> -> {ok, 6}; <<"7"/utf8>> -> {ok, 7}; <<"8"/utf8>> -> {ok, 8}; <<"9"/utf8>> -> {ok, 9}; <<"a"/utf8>> -> {ok, 10}; <<"A"/utf8>> -> {ok, 10}; <<"b"/utf8>> -> {ok, 11}; <<"B"/utf8>> -> {ok, 11}; <<"c"/utf8>> -> {ok, 12}; <<"C"/utf8>> -> {ok, 12}; <<"d"/utf8>> -> {ok, 13}; <<"D"/utf8>> -> {ok, 13}; <<"e"/utf8>> -> {ok, 14}; <<"E"/utf8>> -> {ok, 14}; <<"f"/utf8>> -> {ok, 15}; <<"F"/utf8>> -> {ok, 15}; _ -> {error, nil} end. -spec parse_hex_code_aux(list(binary()), list(integer())) -> list(integer()). parse_hex_code_aux(Char_list, Int_list) -> case Char_list of [] -> Int_list; [_] -> Int_list; [First, Second | Remaining] -> First_result = hex_value(First), Second_result = hex_value(Second), case {First_result, Second_result} of {{ok, First_value}, {ok, Second_value}} -> parse_hex_code_aux( Remaining, lists:append( Int_list, [(16 * First_value) + Second_value] ) ); {_, _} -> [] end end. -spec parse_hex_code(list(binary())) -> list(integer()). parse_hex_code(Value) -> parse_hex_code_aux(Value, []). -spec parse_color_aux(list(integer()), binary()) -> binary(). parse_color_aux(Value, String) -> case Value of [Last] -> <<<>/binary, "m"/utf8>>; [First | Remaining] -> parse_color_aux( Remaining, <<<>/binary, ";"/utf8>> ); [] -> String; _ -> String end. -spec parse_color(types:color()) -> {ok, binary()} | {error, nil}. parse_color(Color) -> Char_list = gleam@string:to_graphemes(erlang:element(2, Color)), case gleam@list:pop(Char_list, fun(_) -> true end) of {ok, {<<"#"/utf8>>, Hex_code}} -> case erlang:length(Hex_code) of 6 -> {ok, parse_color_aux(parse_hex_code(Hex_code), <<""/utf8>>)}; _ -> {error, nil} end; {error, _} -> {error, nil}; _ -> {error, nil} end. -spec get_ansi_code(types:color()) -> binary(). get_ansi_code(Color) -> case gleam@string:lowercase(erlang:element(2, Color)) of <<"clear"/utf8>> -> <<"clear"/utf8>>; _ -> case parse_color(Color) of {ok, Value} -> Value; {error, _} -> <<"clear"/utf8>> end end.