import disnake
import requests
import datetime
import time
from helpers import sql_get
def lfll(parent):
    embed = disnake.Embed(title="Looking for Liege Lords")
    embed.description = "List of people looking for LL, use /LL anywhere you you have access to add to this list!\n **Open the thread below and ✅ the requests that you fulfill**"
    requests = sql_get("SELECT * FROM llrequests WHERE parentID = {parentID} AND fulfilled = '0'".format(parentID=parent))
    if len(requests) > 0:
        users = {}
        userCP = {}
        for entries in  requests:
            if entries[7] in users.keys():
                if entries[4] > userCP[entries[7]]:
                    userCP[entries[7]] = entries[4]
                users[entries[7]].append(entries[2])
            else:
                users[entries[7]] = [entries[2]]
                userCP[entries[7]] = entries[4]
        for name,user in users.items():
            field_body = ""
            for villa in user:
                field_body += ">{villa}\n".format(villa=villa)
            embed.add_field(name="{name} CP:{cp}".format(name=name,cp=userCP[name]),value=field_body)

    return embed

def check_player(user):
    activity = requests.get('https://shk.azure-api.net/shkinfo/v1/UserActivity?world=World%202&username={user}&Key=5E78CFC8-1FFA-4036-8427-D94ED6E1A45B&subscription-key=ff2e578e119348ea8b48a2acd2f5a48d'.format(user=user))
    banStatus = requests.get('http://login.strongholdkingdoms.com/ajaxphp/username_search.php?term={user}'.format(user=user))
    shield = requests.get('https://login.strongholdkingdoms.com/ajaxphp/get_shield_url.php?username={user}&transparent=1'.format(user=user))
    print(banStatus.text)
    banned = "Account is **BANNED**"
    act = "Error"
    shieldURL=''
    known = False
    if 'error' not in shield.json().keys():
        shieldURL = shield.json()['url']
        known = True
    if len(banStatus.text) == 2:
        banned = "Account is **BANNED**"
        if not known:
            banned = "Account is unknown, typo?"
        
    else:
        result = banStatus.json()
        check = user.lower()
        if check in (string.lower() for string in result):
            banned = "**NOT** Banned"
    if activity.text == '01/Jan/0001 00:00:00':
        print("Unknown player")
        act = "-No W2 Data-"
    else:
        date = datetime.datetime.strptime(activity.text,'%d/%b/%Y %H:%M:%S')
        print(date)
        act = '<t:{t1}:R>'.format(t1=int(date.timestamp()))
    embed = disnake.Embed(title="{user}'s info".format(user=user))
    embed.description = "Generated <t:{t1}:R>\nCurrent avaliable info is:".format(user=user,t1=int(time.time()))
    embed.add_field(name="Last Activity",value = act)
    embed.add_field(name="Status",value=banned)
    if shieldURL == '':
        embed.set_thumbnail(file=disnake.File('StormBrigade_White.png'))
    else:
        embed.set_thumbnail(url=shieldURL)
    return embed