'''
Author: your name
Date: 2021-07-12 11:14:48
LastEditTime: 2021-07-19 19:25:09
LastEditors: Please set LastEditors
Description: In User Settings Edit
FilePath: \evm-store\tools\build_out\controllers\appi.py
'''
import os
import re
import json
import shutil
from pprint import pprint
from pathlib import Path
from datetime import datetime
from application.app import db, config
from models.annex import AnnexModel
from models.app import AppModel
from models.user import UserModel
from models.package import PackageModel
from webcreator.log import logger
from webcreator.utils.epk import EpkApp
from webcreator.response import ResponseCode

class BuildAppResource(object):
    def __init__(self):
        super().__init__()

    def post(self, params, files=[]):
        logger.info(params)

        user = UserModel.query.filter(UserModel.uuid==params.get("access_key")).one_or_none()
        if not user:
            return False, ResponseCode.USER_NOT_EXISTS

        print(user)

        params.update({
            'app_icon': params.get('app_icon', ''),
            'create_by': user.id,
            'create_at': datetime.now(),
            'update_by': user.id,
            'update_at': datetime.now(),
        })

        props = dict()
        for p in params:
            if hasattr(AppModel, p):
                props[p] = params[p]

        # logger.info(props)
        # pprint(props)
        app = AppModel(**props)
        db.session.add(app)
        db.session.commit()

        dir_format = "{}-{}-{}".format(app.app_name, app.app_version, datetime.now().strftime("%Y%m%d%H%M%S"))
        target_dir = Path(config.EPK_DIR).joinpath(user.account).joinpath(dir_format)
        dest_dir = target_dir.joinpath("src")
        if not dest_dir.exists():
            os.makedirs(dest_dir.resolve().as_posix())

        for target_file in files:
            filename = os.path.basename(target_file)
            name, suffix = os.path.splitext(filename)
            name = re.sub(r"_\d{14}$", "", name)
            dst_file = dest_dir.joinpath(name + suffix)
            shutil.copy(os.path.normpath(target_file), dst_file.resolve().as_posix())

            res = AnnexModel(app=app.id, title=filename, path=dst_file.relative_to(config.UPLOAD_ROOT_DIR).resolve().as_posix(), size=dst_file.stat().st_size, create_by=user.id, create_at=datetime.now(), update_by=user.id, update_at=datetime.now())
            db.session.add(res)
            db.session.flush()
        db.session.commit()

        # 打包成EPK文件
        app_info = {}
        params = { 'appName': app.app_name, 'appDir': dest_dir.resolve().as_posix(), 'appVersion': app.app_version, 'output': target_dir.resolve().as_posix() }
        if user.role == 1:
            params['algorithm'] = "h"
        epk = EpkApp(**params)
        app_info = epk.pack()
        app_info['md5'] = str(app_info['md5'])

        # 更新数据库对应文件路径
        # 将文件拷贝过去后，需要重新更新数据库文件记录
        epk_path = target_dir.relative_to(config.UPLOAD_ROOT_DIR).joinpath("{}.epk".format(app.app_name)).resolve().as_posix()

        result = PackageModel.query.filter(PackageModel.app==app.id).one_or_none()
        if result:
            result.app_path = epk_path
            result.app_info = app_info
            result.update_by = user
            result.update_at = datetime.now()
            db.session.commit()
        else:
            result = PackageModel(app=app.id, file_path=epk_path, package_info=json.dumps(app_info, ensure_ascii=False), app_version=params.get("app_version", '1.0.0'), source=2, create_by=user.id, create_at=datetime.now(), update_by=user.id, update_at=datetime.now())
            db.session.add(result)
            db.session.commit()

        target_dir.joinpath("epk.json").write_text(json.dumps(app.to_dict(), ensure_ascii=False))
        # with open(os.sep.join([target_dir, "epk.json"]), "w") as f:
        #     json.dump(app.to_dict(), f)

        return { 'app_name': app.app_name, 'app_file': "{}.epk".format(app.app_name), 'app_url': epk_path }, ResponseCode.HTTP_SUCCESS

buildAppResource = BuildAppResource()

class AppReview(object):
    def __init__(self):
        super().__init__()

    def post(self, app, review, jwt={}):
        user = UserModel.query.filter(UserModel.uuid==jwt.get("uuid")).one_or_none()
        if not user:
            return None, ResponseCode.USER_NOT_EXISTS

        app = AppModel.query.filter(AppModel.uuid==app).one_or_none()
        if not app:
            return None, ResponseCode.APPLICATION_NOT_EXISTS

        app.app_review = review
        app.update_at = datetime.now()
        app.update_by = user.id
        db.session.commit()
        return True, ResponseCode.HTTP_SUCCESS

appReview = AppReview()