from scratchcommunication.cloud import TwCloudConnection
import time as t

translate=[
    " ",
    "A",
    "B",
    "C",
    "D",
    "E",
    "F",
    "G",
    "H",
    "I",
    "J",
    "K",
    "L",
    "M",
    "N",
    "O",
    "P",
    "Q",
    "R",
    "S",
    "T",
    "U",
    "V",
    "W",
    "X",
    "Y",
    "Z",
    "a",
    "b",
    "c",
    "d",
    "e",
    "f",
    "g",
    "h",
    "i",
    "j",
    "k",
    "l",
    "m",
    "n",
    "o",
    "p",
    "q",
    "r",
    "s",
    "t",
    "u",
    "v",
    "w",
    "x",
    "y",
    "z",
    "0",
    "1",
    "2",
    "3",
    "4",
    "5",
    "6",
    "7",
    "8",
    "9",
    "`",
    "~",
    "!",
    "@",
    "#",
    "$",
    "%",
    "^",
    "&",
    "*",
    "(",
    ")",
    "-",
    "_",
    "=",
    "+",
    "[",
    "{",
    "]",
    "}",
    "\\",
    "|",
    ";",
    ":",
    "'",
    '"',
    ",",
    "<",
    ".",
    ">",
    "/",
    "?",
    "§",
    "...",
    "�",
    "dot"
]

conn=TwCloudConnection(project_id="1254831739",username="pythoncode",contact_info="get that yourself idiot",)

def imggen(item,text):
    content=item
    # Read the entire content of the file as a single string
    input_str=content
    # Clean input: remove spaces and newlines
    cleaned = input_str.replace(" ", "").replace("\n", "")
    ret = ""
    # Process in groups of 3 bits
    for i in range(0, len(cleaned), 3):
        group = cleaned[i:i+3]
        if len(group) == 3:
            num = int(group, 2)  # Convert 3-bit binary to decimal (0-7)
            ret += str(num)
        # If partial group at end, you could handle it (e.g., pad with 0s or skip)
    return "".join(["/img§",ret,"§",text])

def trsend(inp):
    temp=""
    ret=""
    for i in range(0,len(inp)):
        try:
            temp=str(translate.index(inp[i]))
        except Exception:
            temp="97"
        if int(temp)<10:
            temp="0"+temp
        ret=ret+temp
    return ret

def trget(inp):
    ret=""
    for i in range(0,len(inp),2):
        ret=ret+str(translate[int(str(inp[i])+str(inp[i+1]))])
    return ret

def sendmessage(username,color,brightness,str,variable="room1"):
    conn.set_variable(name=variable,value=trsend(f"{color}§{brightness}§{username}§"+str)) #type:ignore

def getmessage(variable="room1"):
    temp1=trget(conn.get_variable(name=variable))
    temp2=temp1.split("§")
    try:
        return temp2
    except IndexError:
        return temp1
    
def sendping(name,color,variable="room1ping"):
    ts = str(int(t.time()*1000))
    conn.set_variable(name=variable,value=trsend(ts+f"§{name}§{color/16}")) #type:ignore