from time import sleep
import subprocess
from flask import Flask, Response, redirect, url_for, request, session, abort, render_template
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger
from flask_login import LoginManager, UserMixin, login_required, login_user, logout_user 
import json
password = "RandomPassword"
secret = "fe18d16cff64b8124792b8d512cecf90b79c4947707815ecf5c70446fdbc5101"
"""
Automatic start of MsRewards
"""
scheduler = BackgroundScheduler()
scheduler.start()
trigger = CronTrigger(
    year="*", month="*", day="*", hour="2", minute="25", second="25"
)
def start_ms():
    subprocess.Popen(["python3", "./V6.py", "-v", "2345"])
scheduler.add_job(
        start_ms,
        trigger=trigger,
        #args=["hello world"],
        name="Daily start",
)
"""
Flask app
"""
app = Flask(__name__)
"""
Login stuff
"""
# TODO : changer le secret
# config
app.config.update(
    SECRET_KEY = secret
)
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = "login"
# silly user model
class User(UserMixin):
    def __init__(self, id):
        self.id = id
        self.name = "user" + str(id)
        self.password = password
        
    def __repr__(self):
        return "%d/%s/%s" % (self.id, self.name, self.password)
users = [User(1)]
@app.route("/login/", methods=["GET", "POST"])
def login():
    if request.method == 'POST':
        if request.form['password'] == password:
            user = User(id)
            login_user(user)
            return(render_template("override.html"))
        else:
            return abort(401)
    else:
        return(render_template("login.html"))
# handle login failed
@app.errorhandler(401)
def page_not_found(e):
    return(render_template("login.html"))
    
    
# callback to reload the user object        
@login_manager.user_loader
def load_user(userid):
    return User(userid)
"""
end of login stuff
"""
@app.route("/", methods=["post"])
def dev():
    action = request.form
    print(action)
    if action == "dev":
        print("dev action test")
    return(f"
 TO IMPLEMENT - {action}
")
@app.route("/")
def main():
    return(render_template("override.html"))
@app.route("/discord/")
def discord_get():
    with open("./user_data/discord.json", "r") as inFile:
        data = json.load(inFile)
    return(render_template("discord.html", data=data, len=len(data)))
@app.route("/discord/", methods=["post"])
def discord_post():
    with open("./user_data/discord.json", "r") as inFile:
        data = json.load(inFile)    
    action = request.form
    config = action["select"]
    successL = action["successL"]
    try :
        a = action["successT"] 
        successT = "True"
    except:
        successT = "False"
    try :
        a = action["errorsT"] 
        errorsT = "True"
    except:
        errorsT = "False"
    errorsL = action["errorsL"]
    name = action["name"] if action["name"] else f"unnamed{action['select']}"
    data[config] = {"errorsL" : errorsL, "errorsT": errorsT, "successT": successT, "successL": successL, "name": name}
    with open("./user_data/discord.json", "w") as outFile:
        json.dump(data, outFile)
    return(render_template("discord.html", data=data, len=len(data)))
@app.route("/dev/")
def dev2():
    with open("./user_data/proxy.json", "r") as inFile:
        j = json.load(inFile)
    new_proxy = {"address": "ADDRESS", "port": "PORT", "name":"NAME"}
    max_index = 0
    for i in range(1, 50):
        try :
            print(j[str(i)])
        except :
            print(f"found {i - 1} proxys")
            max_index = i
            break
    j[f"{max_index}"] = new_proxy
    print(j)
    with open("./user_data/proxy.json", "w") as outfile:
        json.dump(j, outfile)
    return(render_template("dev.html"))
@app.route("/settings/")
def settings_get():
    with open("./user_data/settings.json", "r") as inFile:
        settings = json.load(inFile)
    return(render_template("settings.html", data=settings))
@app.route("/settings/", methods=["post"])
def settings_post():
    settings = {}
    action = request.form
    settings['avatarlink'] = action["avatarlink"]
    with open("./user_data/settings.json", "w") as inFile:
        json.dump(settings, inFile)
    return(render_template("settings.html", data=settings))
@app.route("/proxy/")
def proxy_get():
    with open("./user_data/proxy.json", "r") as inFile:
        j = json.load(inFile)
    return(render_template("proxy.html", data=j, len=len(j)))
@app.route("/proxy/", methods=["post"])
def proxy_post():
    with open("./user_data/proxy.json", "r") as inFile:
        data = json.load(inFile)    
    action = request.form
    try :
        config = action["select"]
        address = action["address"]
        port = action["port"]
        name = action["name"] if action["name"] else f"@unnamed{action['select']}"
        data[config] = {"address" : address, "port": port, "name": name}
    except :
        print("error : probably bad config")
    with open("./user_data/proxy.json", "w") as outFile:
        json.dump(data, outFile)
    return(render_template("proxy.html", data=data, len=len(data)))
@app.route("/override/")
def override_get():
    return(render_template("override.html"))
@app.route("/override/", methods=["post"])
def override():
    subprocess.run(["python3", "./V6.py", "-v", "2345"])
    return(render_template("override.html"))
@app.route("/database/")
def database_get():
    with open("./user_data/database.json", "r") as inFile:
        database = json.load(inFile)
    return(render_template("database.html", data = database))
@app.route("/database/", methods=["post"])
def database_post():
    action = request.form
    data = {
        "host": action['address'],
        "table": action['table'],
        "usr": action['user'],
        "pwd": action['password'],
        "checked": ""
        }  
    try :
        if action["switch"] :
            data['checked'] = "checked"
    except:
        pass
    with open("./user_data/database.json", "w") as inFile:
        json.dump(data, inFile)
    return(render_template("database.html", data = data))
@app.route("/accounts/")
def accounts_get():
    with open("./user_data/proxy.json", "r") as inFile:
        proxys = json.load(inFile)
    with open("./user_data/discord.json", "r") as inFile:
        discords = json.load(inFile)
    with open("./user_data/configs.json", "r") as inFile:
        configs = json.load(inFile)
    return(render_template("accounts.html", data=configs, discords=discords, proxys=proxys, configs=configs, len=len(configs)))
@app.route("/accounts/", methods=["POST"])
def accounts_post():
    action = request.form
    with open("./user_data/proxy.json", "r") as inFile:
        proxys = json.load(inFile)
    with open("./user_data/discord.json", "r") as inFile:
        discords = json.load(inFile)
    with open("./user_data/configs.json", "r") as inFile:
        configs = json.load(inFile)
    comptes = {
        "1":{"mail": action["mail1"], "pwd": action["pwd1"], "2fa": action["2fa1"]},
        "2":{"mail": action["mail2"], "pwd": action["pwd2"], "2fa": action["2fa2"]},
        "3":{"mail": action["mail3"], "pwd": action["pwd3"], "2fa": action["2fa3"]},
        "4":{"mail": action["mail4"], "pwd": action["pwd4"], "2fa": action["2fa4"]},
        "5":{"mail": action["mail5"], "pwd": action["pwd5"], "2fa": action["2fa5"]}
    }
    configs[action["config"]] = {
        "name" : action["name"] if action["name"] != "" else f"unnamed{action['config']}",
        "proxy": action["proxy"],
        "discord": action["discord"],
        "accounts": comptes
        }
    with open("./user_data/configs.json", "w") as outFile:
        json.dump(configs, outFile)
    return(render_template("accounts.html", data=configs, discords=discords, proxys=proxys, configs=configs, len=len(configs)))
def read_config_txt(ligne):
    f = open("./user_data/config.cfg", "r")
    txt = f.readlines()
    f.close()
    if txt.count(txt) >1:
        raise NameError("Fail")
    
    for i in range(len(txt)) :
        name = txt[i].split(" = ")[0]
        if name == ligne:
            ret = txt[i].split(" = ")[1]
    f = open("./user_data/config.cfg", "w")
    for i in txt :
        f.write(i)
    f.close()
    return(ret.replace("\n", ""))
def edit_config_txt(ligne, contenu):
    f = open("./user_data/config.cfg", "r")
    txt = f.readlines()
    f.close()
    if txt.count(txt) >1:
        raise NameError("Fail")
    
    for i in range(len(txt)) :
        name = txt[i].split(" = ")[0]
        if name == ligne:
            txt[i] = name + " = " + str(contenu) + "\n"
    f = open("./user_data/config.cfg", "w")
    for i in txt :
        f.write(i)
    f.close()
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=3456, debug=True)