import time, json, os, sys
from __main__ import *
from datetime import datetime
import css
v.reload(css.__name__)
#try: del sys.modules["css"], css
#except: import css





def iterate_through_clients(out):
    returncontent = {}
    for numberofclients, client in enumerate(v.clients.copy()):
        if not "0x" in client: continue
        returncontent.setdefault(client, {})
        returncontent[client] = {
       "ip": v.clients.get(client, {}).get("ip", "None"),
       "from": v.clients.get(client, {}).get("From", "None"),
       "station": v.clients.get(client, {}).get("station", "None"),
       "siteid": v.clients.get(client, {}).get("Siteid", "None"),
       "osversion": v.clients.get(client, {}).get("OS-Version", "8"),
       "uptime": v.clients.get(client, {}).get("Uptime", "None"),
       "timestamp": v.clients.get(client, {}).get("timestamp", "None"),
       "temperature": v.clients.get(client, {}).get("temperature", "None"),
       "country": v.clients.get(client, {}).get("Country", "se"),
       "operator": v.clients.get(client, {}).get("Operator", "sl"),
        "mac" : str(client).replace("x",""),
        "timestamp": v.clients.get(client, {}).get("timestamp","a")
       }
        
        
    out += f"""Antal klienter: {str(numberofclients)} <br>"""

    for i in returncontent:
        out += returncontent[i]["mac"] + " " + returncontent[i]["ip"] + " "
        out += returncontent[i]["country"] + "/" + returncontent[i]["operator"] + " - "
        out += str(returncontent[i]["timestamp"]) + " - "
        if not returncontent[i]["siteid"] == "None": out += returncontent[i]["siteid"] + "<br>"
        elif not returncontent[i]["from"] == "None": out += returncontent[i]["from"] + "<br>"
        elif not returncontent[i]["station"] == "None": out += returncontent[i]["station"] + "<br>"
    return out

"""def generate_content():
    out = json.dumps(v.clients.copy())
    #out = "<html>"
    #out += iterate_through_clients(out)
    #out += "</html>" 
    return  out"""

def generate_content():
    clients = v.clients.copy()
    clients["online"] = v.online
    out = json.dumps(clients)
    #out = "<html>"
    #out += iterate_through_clients(out)
    #out += "</html>" 
    return  out


##########################################
try: 
    content = generate_content()
except Exception as e:
    content = str(e)
with open("clients.dat","w") as f:
    f.write(str(json.dumps(v.clients.copy())))
with open("operators.dat","w") as f:
    f.write(str(json.dumps(v.operators.copy())))

# <iframe src="http://data.t-skylt.se:89/settings?balance" style='width: 100%; height: 400px' ></iframe>


def online_code():
    out = f'''print("Starting T-Monitor...")
from __main__ import *
from load_screen import *
data = "None"
time.sleep(1)
try: stars += 1
except: stars = 1
try: data = """{json.dumps(str(v.clients.copy()))}"""
except Exception as e: pprint(e)
print(data)
print("Ending")
'''
    return out

def params(request):
    #if "lookup" in request.path:
    #    return "test"
    if "run" in request.path:
        out = online_code()
        return out
    if "clients" in request.path:
        out = str(json.dumps(v.clients.copy()))
        return  out# str(numberofclients) + str(returncontent) + str(v.clients)
    if "ftp" in request.path: 
        v.ftp = True
        import subprocess
        script_path = "/var/www/html/ftp.sh"
        try: subprocess.run([script_path], shell=True)
        except Exception as e:
            return str(e)
        return '''<html><meta http-equiv="refresh" content="1; URL=http://data.t-skylt.se:89/settings" /></html>'''
    if "restart" in request.path: 
        print("Attempting restart...............")
        #########
        with open("db.dat","w") as f:
            f.write(json.dumps(v.operators))
        ########
        import subprocess
        script_path = "/var/www/html/restart.sh"
        try: subprocess.run([script_path], shell=True)
        except Exception as e:
            return str(e)
        return '''<html><meta http-equiv="refresh" content="1; URL=http://data.t-skylt.se:89/settings" /></html>'''
    if "balance" in request.path:
        try: del sys.modules["balance"], balance
        except: import balance
        return balance._balance(request)

        
    if "delstation" in request.path:
        station = request.path.split("delstation")[1]
        for char in v.html_decode:
            station = station.replace(char, v.html_decode[char])
        print(station)
        del saved_data["seen_stations"][station]
        with open("data.dat", "w", encoding='utf-8') as f:
            f.write(json.dumps(saved_data))
    elif "dump" in request.path: return str(v.departures)
    elif "stations" in request.path:
        import requests
        station = "Gbpg"
        key = "63ea83cd2cce48c79eaebf475818b7d0"
        msg = """<REQUEST>
        <LOGIN authenticationkey='63ea83cd2cce48c79eaebf475818b7d0'/>
        <QUERY objecttype='TrainStation' schemaversion='1'>
        <FILTER/>
        <INCLUDE>Prognosticated</INCLUDE>
        <INCLUDE>AdvertisedLocationName</INCLUDE>
        <INCLUDE>LocationSignature</INCLUDE>
        </QUERY>
        </REQUEST>"""
        response = requests.post("https://api.trafikinfo.trafikverket.se/v2/data.json", data=msg, headers={'Content-Type': 'text/xml'})
        stations = json.loads(response.text)
        stations_dict = {}
        for i in stations:
            for ii in stations[i]["RESULT"][0]["TrainStation"]:
                name = ii["AdvertisedLocationName"]
                short_name = ii["LocationSignature"]
                stations_dict[short_name] = name
                #stations_dict[name] = short_name
        return json.dumps(stations_dict)
    #elif "active" in request.path: return str(v.siteids.active_stations)
    elif "active" in request.path: return str(active_stations)
    elif "monitor" in request.path: 
        _errors = []
        for e in v.errors:
            if  not "_html" in str(v.errors[e][len(v.errors[e])-1]): _errors.append(e)
            #if not "_html" in str(e): _errors.append(e)
        online = json.dumps(v.online)
        #online = ""
        x = json.dumps([saved_data["no_of_clients"], saved_data["max_clients"], mean_ping, _mean, len(_errors), online])
        return str(x)
    
    elif "operators" in request.path: return str(v.operators)
    elif "adduser" in request.path:
        #try:
        #    with open("users.dat", "r") as f:
        #        all_users = json.loads(f.read())
        #except: 
        #    all_users = {}
        #    with open("users.dat","w") as f:
        #        f.write(json.dumps(all_users))
        #    return "Creating new JSON"
        try:
            new_user = request.path.split("=")[1]
            v.all_users[new_user] = {"date":str(datetime.now())[:10], "mac":False}
            
            #return str(all_users)
            with open("users.dat","w") as f:
                f.write(json.dumps(v.all_users))
            return str(v.all_users)
        except Exception as e: 
            return str(e) + "\n\n" + str(v.all_users)
            pass
        return str(v.all_users)
            
        #with open("users.dat","w") as f:
        #    f.write(json.dumps(all_users))
        #return str(all_users)

        print(all_users)
        #user = request.path.split("=")[1]
        #user = json.loads(user)
        

    elif "stop" in request.path:
        import os
        os._exit(os.EX_OK)
    elif "reload" in request.path:
        try: reload(v.__name__)
        except: pass
        return ""
    elif "ad" in request.path:
        try:
            _ad = request.path.split("=")[1]
            if _ad:
                v.ad[0] = True
                v.ad[1] = request.path.split("=")[1]
                return content
            else: 
                v.ad[0] = False
                v.ad[1] = ""
                return content
        except: pass
        #v.ad = [False, "Köp tandkräm"]
        return json.dumps(v.ad)
    elif "cache" in request.path: return str(v.cache)
    
    elif "siteids" in request.path: return str(v.siteids.siteId)
    elif "data" in request.path: return(str(saved_data))
    elif "stats" in request.path: return stats_page()
    elif "callout" in request.path:
        v.callout_message = str(request.path).split("callout=")[1]
        for char in v.html_decode:
            v.callout_message = v.callout_message.replace(char, v.html_decode[char])
        if not len(v.callout_message): v.callout_message = False
        load_deviations()
    elif "clear_errors" in request.path:
        v.errors = {}
    
    elif "send" in request.path:
        print(request.path)
        mac_id = request.path.split("send=")[1]
        mac_id = mac_id.split("=")[0]
        message = request.path.split("msg")[1]
        for char in v.html_decode:
            message = message.replace(char, v.html_decode[char])
        if len(message): v.direct_messages[mac_id] = message
        else: del v.direct_messages[mac_id]
        print(mac_id)
        print(message)
    elif "variable" in request.path:
        variable = request.path.split("=")[1]
        try: return str(eval(variable))
        except: return "Error"
        
    elif "departures" in request.path:
        list_of_departures = ""
        for country in v.operators:
            for operator in v.operators[country]:
                for siteid in v.operators[country][operator]:
                    if "name" in v.operators[country][operator][siteid]: _name = v.operators[country][operator][siteid]["name"]
                    else: 
                        try: _name = _siteid[siteid]
                        except: _name = ""
                    if "departures" in v.operators[country][operator][siteid]:
                        list_of_departures += "\n" + _name + " " + siteid + " " + str(len(v.operators[country][operator][siteid]["departures"]))
        return list_of_departures

    elif "mac_id" in request.path:
        mac_id = request.path.split("?mac_id=")[1].replace("0x","")
        print(mac_id)
        return """
<html>

  <label for="fname">Direktmeddelande till """+mac_id+""":</label><br>
  <input type="text" id="direct_message" value=""><br><br>
  <button onclick="window.location.href='settings?send="""+mac_id+"""=msg'+encodeURIComponent(document.getElementById('direct_message').value)"> &#129146;/&#10060;</button>

</html>"""
    
    elif "shop" in request.path: 
        if "supported" in request.path:
            return """<html><div style="background: black; color:white; padding: 0px; margin:0px">
<center>
Supported regions: 
<img src="https://cdn.shopify.com/s/files/1/0904/0235/7512/files/se_430x.png?v=1732310677#" style="width: 15px">


<img src="https://cdn.shopify.com/s/files/1/0904/0235/7512/files/dk_430x.png?v=1732310677#" style="width: 15px">


<img src="https://cdn.shopify.com/s/files/1/0904/0235/7512/files/de_430x.png?v=1732310677#" style="width: 15px">

<img src="https://cdn.shopify.com/s/files/1/0904/0235/7512/files/fi_430x.png?v=1732310677#" style="width: 15px">


</center>
</div></html>"""
        return "SHOP"
    return content
