'''
Author: your name
Date: 2021-04-14 14:12:18
LastEditTime: 2021-06-29 20:21:46
LastEditors: Please set LastEditors
Description: In User Settings Edit
FilePath: \evm-store\backend\controller\api_manager.py
'''
#!/usr/bin/env python
# -*- coding: utf_8 -*-

import os
import logging
import shutil
from datetime import datetime
from pony.orm import *
from app.setting import config
from model.user import User
from utils import md5_salt

logger = logging.getLogger(__name__)

class ApiManager(object):
    def __init__(self):
        super(ApiManager, self).__init__()

    def update_user_password(self, user, data):
        with db_session:
            editor = User.get(id=user)
            if not editor:
                return False, "current user is not exists"

            result = User.get(uuid=data.get("uuid"), password=md5_salt(data['password']))

            if not result:
                return None, "user does not exists"

            data.pop("uuid")
            data['password'] = md5_salt(data['newPassword'])
            data.pop('newPassword')
            data.update({
                "create_by": editor.id,
                "create_at": datetime.now(),
                "update_by": editor.id,
                "update_at": datetime.now()
            })

            result = result.set(**data)
            commit()

            return True, "success"

    def get_escape_text(self, data):
        fname = "./a.c"
        target = os.sep.join(["out", fname])

        if os.path.exists(fname):
            os.remove(fname)

        if os.path.exists(target):
            os.remove(target)

        with open(fname, "w+") as f:
            f.write(data['string'])

        result = os.system("./opqcp {i} ./out".format(i=fname))
        print(result)

        with open(target) as f:
            result = f.read()

        return result

        # return convert_string(data['string'])

    def opqcp(self, params):
        target_file = os.path.normpath(os.sep.join([config.get("UPLOAD_PATH"), params.get("filename")]))

        shutil.copy(target_file, os.getcwd())

        # dtNowString = datetime.now().strftime("%Y%m%d%H%M%S%f")
        # fn, ex = os.path.splitext(params.get("filename"))

        output_path = os.sep.join([os.path.dirname(target_file), "out"])
        if not os.path.exists(output_path):
            os.makedirs(output_path)

        print("#######", output_path)
        # print(os.path.dirname(os.getcwd()), os.path.abspath("../opqcp/opqcp"))

        result = os.system("./opqcp {i} ./out".format(i=os.path.basename(target_file)))
        print(result)

        # command = ["./opqcp", os.path.basename(target_file), "./"]
        fname = os.sep.join([os.getcwd(), "out", os.path.basename(target_file)])
        shutil.copy(fname, output_path)
        os.remove(fname)
        
        # ret = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf-8", timeout=5)
        # if ret.returncode == 0:
        #     print("success:", ret)
        # else:
        #     print("error:", ret)

        # ret = target_file

        return True, os.sep.join([output_path.replace(config.get("UPLOAD_PATH"), ""), params.get("filename")])

apiManager = ApiManager()
