import gc
from flask import Flask, render_template, request, current_app
import configparser
from controller.Main import Main  # 导入全部蓝图变量
import datetime
from apscheduler.schedulers.blocking import BlockingScheduler
from datetime import datetime
from dao.Conn import ConnMySql
import sys
import io


# 清除登录状态
def clearLoginStateIn24H():
    conn = ConnMySql()
    conn.userClearLoginStateIn24H()
    print("清除登录状态-" + datetime.now().strftime("%Y-%m-%d %H:%M:%S"))


app = Flask(__name__)  # 初始化Flask对象
app.register_blueprint(Main)  # 将所有蓝图对象注册到app这个flask对象内

# 上传文件最大16M字节
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024

# App配置信息，键=段名+键名，如：db.port=3306
cfg = configparser.ConfigParser()
cfg.optionxform = str  # 保持配置文件中键的大小写
cfg.read("static/conf/sys.ini", encoding='utf-8')
sections = cfg.sections()
for section in sections:
    items = cfg.items(section)
    for key, val in items:
        app.config[section + '.' + key] = val

# 个别取值进行特殊处理
app.config['db.port'] = int(app.config['db.port'])
if app.config['sys.useProxy'] == "0":
    app.config['sys.useProxy'] = False
else:
    app.config['sys.useProxy'] = True

app.config['sys.proxyid'] = 0 #当前使用的代理id
app.config['sys.userid'] = 0 #当前使用的账号id

sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

if __name__ == '__main__':
    # webbrowser.open("0.0.0.0:5000")
    app.run(host='0.0.0.0', port=5201, debug=True)  # 启动入口
    # 启动定时任务，定时清除异常登录状态，每半小时一次
    # sched = BlockingScheduler()
    # sched.add_job(clearLoginStateIn24H, 'interval', seconds=1800, id='task-clearLoginStateIn24H')
    # sched.start()
