'''
Author: your name
Date: 2021-07-12 11:14:48
LastEditTime: 2021-07-12 11:29:36
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 urllib import parse
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 import utils
from webcreator.utils.epk import EpkApp
from webcreator.response import ResponseCode

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

    def post(self, params, jwt={}):
        logger.info(params)

        user = UserModel.query.filter(UserModel.id==jwt['id'])
        if not user:
            return False, ResponseCode.USER_NOT_EXISTS

        if params.get("access_key"):
            params.pop("access_key")

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

        app = AppModel(**params)
        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"))
        upload_dir = os.sep.join([config.UPLOAD_ROOT_DIR, "evueapps"])
        target_dir = os.sep.join([upload_dir, user.account, dir_format])
        dest_dir = os.sep.join([target_dir, "src"])
        if not os.path.exists(dest_dir):
            os.makedirs(dest_dir)

        for target_file in params.get('files'):
            filename = os.path.basename(target_file)
            name, suffix = os.path.splitext(filename)
            name = re.sub(r"_\d{14}$", "", name)
            dst_file = os.path.normpath(os.sep.join([dest_dir, name + suffix]))
            shutil.copy(os.path.normpath(target_file), dst_file)

            res = AnnexModel(app=app, title=filename, path=dst_file.replace(config.UPLOAD_ROOT_DIR, ""), size=os.path.getsize(dst_file), create_by=user, create_at=datetime.now(), update_by=user, 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, 'appVersion': app.app_version, 'output': target_dir }
        if user.role == "administrator" or user.role == "community":
            params['algorithm'] = "h"
        epk = EpkApp(**params)
        app_info = epk.pack()
        app_info['md5'] = str(app_info['md5'])

        # 更新数据库对应文件路径
        # 将文件拷贝过去后，需要重新更新数据库文件记录
        epk_path = os.sep.join([target_dir.replace(config.UPLOAD_ROOT_DIR, ""), "{}.epk".format(app.app_name)]).replace('\\', '/')

        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=app_info, app_version=params.get("app_version"), source=2, create_by=user, create_at=datetime.now(), update_by=user, update_at=datetime.now())
            db.session.add(result)
            db.session.commit()

        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': parse.urljoin(config['UPLOAD_SERVER'], epk_path) }, ResponseCode.HTTP_SUCCESS

buildAppResource = BuildAppResource()


