import ujson
import re
import random


def rnd():
    x = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
    return "".join([random.choice(x) for _ in range(32)])


def write_to_json_file(name, data):
    with open(name, 'w') as f:
        ujson.dump(data, f, indent=4)


def write_to_text_file(name, data):
    with open(name, 'w') as f:
        f.write(data)


def apex_response_to_json(response):
    # Use regex somehow
    return None


def get_room_and_sub(response, private=False):
    success = {}
    if response.startswith("//"):
        success['error'] = "#ALREADY_IN_PARTY"
        success['success'] = False
        return success
    try:
        success['room'] = get_convar("partySub", response)
        
        sub_ends_with = "\n"
        success['sub'] = get_convar("party_hostname", response, ends_with=sub_ends_with)
        
        success['error'] = None
        success['success'] = True
    except IndexError:
        regex = r"(?<=details: )[^\n]+"
        success['error'] = re.findall(regex, response, re.MULTILINE)[0]
        success['success'] = False
    return success


def get_convar(convar_name, response, ends_with="\n"):
    regex = rf"(?<={convar_name}: )[^{ends_with}]+"
    convar = re.findall(regex, response, re.MULTILINE)[0]
    return convar.replace('"', '')

import ujson
import re
import random


def rnd():
    x = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
    return "".join([random.choice(x) for _ in range(32)])


def write_to_json_file(name, data):
    with open(name, 'w') as f:
        ujson.dump(data, f, indent=4)


def write_to_text_file(name, data):
    with open(name, 'w') as f:
        f.write(data)


def apex_response_to_json(response):
    # Use regex somehow
    return None


def get_room_and_sub(response, private=False):
    success = {}
    if response.startswith("//"):
        success['error'] = "#ALREADY_IN_PARTY"
        success['success'] = False
        return success
    try:
        success['room'] = get_convar("partySub", response)
        
        sub_ends_with = "\n"
        success['sub'] = get_convar("party_hostname", response, ends_with=sub_ends_with)
        
        success['error'] = None
        success['success'] = True
    except IndexError:
        regex = r"(?<=details: )[^\n]+"
        success['error'] = re.findall(regex, response, re.MULTILINE)[0]
        success['success'] = False
    return success


def get_convar(convar_name, response, ends_with="\n"):
    regex = rf"(?<={convar_name}: )[^{ends_with}]+"
    convar = re.findall(regex, response, re.MULTILINE)[0]
    return convar.replace('"', '')

# Use regex somehow