import os
import sys
import json
import getopt
import shutil
import configparser
from datetime import datetime
from operator import itemgetter

# 应用和数据分离
# 数据库文件备份在evm_app_store_files/epkdb
# 探测文件变化，定时备份到 epkdb

config = configparser.ConfigParser()
config.read(os.path.join(os.getcwd(), "config.ini"))

# 根据文件最后修改时间排序文件
def getSortDir(path):
    lists = os.listdir(path)
    print(lists)
    lists.sort(key=lambda fn: os.path.getmtime(os.sep.join([path, fn])))
    filepath = os.path.join(path, lists[-1])
    print(filepath)
    return lists

def isFileChange(dt):
    f = os.sep.join([os.getcwd(), config.get("database", "filename")])
    if dt:
        return dt != int(os.path.getmtime(f))
    else:
        return int(os.path.getctime(f)) != int(os.path.getmtime(f))

def backupDatabase():
    src = config.get("database", "filename")
    dst = os.path.abspath(config.get("uploads", "upload_path"))
    dst = os.path.normpath(os.sep.join([dst, config.get("uploads", "db_dir")]))
    if not os.path.exists(dst):
        os.makedirs(dst)
    # 判断文件创建时间和修改时间是否一致，不一致则备份
    shutil.copy(src, dst)
    src = os.sep.join([dst, src])
    dst = os.sep.join([dst, f"{datetime.now().strftime('%Y%m%d%H%M%S')}-{config.get('database', 'filename')}"])
    os.rename(src, dst)

def removeExpiredFiles():
    path = os.path.abspath(config.get("uploads", "upload_path"))
    path = os.path.normpath(os.sep.join([path, config.get("uploads", "db_dir")]))

    if not os.path.exists(path):
        os.makedirs(path)

    file_count = len(os.listdir(path))
    if file_count > 10:
        file_list = getSortDir(path)[:-10]
        for f in file_list:
            os.remove(os.sep.join([path, f]))

def getModifyTime():
    result = {}
    with open("./backupData.json", "r+") as f:
        result = json.loads(f.read())
    return result

def saveMofidyTime(result):
    db = config.get("database", "filename")
    result["lastModifyDateTime"] = int(os.path.getmtime(db))
    with open("./backupData.json", "w+") as f:
        f.write(json.dumps(result))
    return result

def main():
    removeExpiredFiles()

    result = getModifyTime()
    if isFileChange(result["lastModifyDateTime"]):
        saveMofidyTime(result)
        backupDatabase()

if __name__ == "__main__":
    main()