import subprocess
import re
import time
import sqlite3
import os
import requests

def get_working_directory():
    # If you see this function, that means you are using the pyinstaller. Use this command to create the executable:
    # pyinstaller -s -F musicstatus-pyi.py --runtime-tmpdir /data/local/tmp
    if os.path.exists("/sdcard/localwrapped"):
        return "/sdcard/localwrapped"
    elif os.path.exists("/storage/emulated/0/localwrapped"):
        return "/storage/emulated/0/localwrapped"
    elif os.path.exists("/data/media/0/localwrapped"):
        return "/data/media/0/localwrapped"
    elif os.path.exists("/mnt/user/0/emulated/0/localwrapped"):
        return "/mnt/user/0/emulated/0/localwrapped"
    else:
        print("Local Wrapped directory not found.")
                
if not os.path.exists(f"{get_working_directory()}/key.txt"):
    print("Key not exist")
    exit()

if not os.path.exists(f"{get_working_directory()}/music.db"):
    try:
        getmusicdb = requests.get("https://halhadus.rocks/assets/localwrapped/music.db")
        with open(f"{get_working_directory()}/music.db", "wb") as f:
            f.write(getmusicdb.content)
    except:
        print("music.db not exist and download failed.")

def get_verification_code():
    try:
        with open(f'{get_working_directory()/key.txt}')
            key = f.read()
            try:
                verifyrequest = requests.post(os.environ["MSSERVER"] + "/verifykey", json={"key": key})
                if verifyrequest.text == "0":
                    print("Verification failed")
                    return None
                elif len(verifyrequest.text) == 64:
                    print("Verification success")
                    return verifyrequest.text
                else:
                    print("Unexpected response")
                    return None
            except:
                print("Can't reach the server.")
                time.sleep(15)
                get_verification_code()
    except:
        print("Key not exist")
        return None

def get_music():
    dumpsys_output = subprocess.check_output("dumpsys media_session", shell=True).decode("utf-8").split("\n")
    if not [line for line in dumpsys_output if "PLAYING" in line]:
        return None
    else:
        description = [line for line in dumpsys_output if "description=" in line]
        try:
            return description[0].split("description=")[1]
        except:
            return None

def get_db_values():
    musicconn = sqlite3.connect(f"{get_working_directory()}/music.db")
    musicc = musicconn.cursor()
    musicc.execute("SELECT * FROM music")
    musicrows = musicc.fetchall()
    musicconn.close()
    musicvalues = []
    for row in musicrows:
        musicvalues.append({
            "listmusicname": row[0],
            "fileartistname": row[4],
            "filealbumname": row[5],
            "filemusictitle": row[6]
        })
    return musicvalues

a = 0
last_written = None
resetstatus = "true"
while True:
    if get_music() == None:
        continue
    last_music = get_music()
    time.sleep(5)
    if last_music == get_music():
        if last_written == last_music:
            continue
        a += 1
        if a == 1:
            for i in get_db_values():
                if i["filealbumname"] == None:
                    full_name = i["filemusictitle"] + ", " + i["fileartistname"] + ", " + "Music"
                else:
                    full_name = i["filemusictitle"] + ", " + i["fileartistname"] + ", " + i["filealbumname"]
                if full_name == last_music:
                    try:
                        verificationcode = get_verification_code()
                        if verificationcode == None:
                            continue
                        requests.post(os.environ["MSSERVER"]  + "/musicstatus.html", json={"music": i["listmusicname"], "time": str(int(time.time())), "verificationcode": verificationcode, "resetstatus": resetstatus})
                        print("Sent")
                        resetstatus = "false"
                    except:
                        print("Can't reach the server.")
                        time.sleep(15)
            last_written = last_music
            a = 0
        continue
    else:
        a = 0
        continue

