# -*- coding:utf-8 -*-
# @Time    : 2020/5/18 9:17 上午
# @Author  : Creat by Han
from Crypto.Cipher import AES
import base64
import configparser
import os
import json

environ = None
try:
    try:
        with open(os.path.expanduser("~/.environ"), "r") as f:
            environ = f.read().strip()
            assert environ
    except:
        with open(os.path.expanduser("F:\.environ.txt"), "r") as f:
            environ = f.read().strip()
            assert environ
except:
    raise Exception("no ~/.environ found! you must create one!")

_ = configparser.ConfigParser()
_flag = None

# 获取项目配置文件
def parse_config_new(config_dir=None):
    dir_name = os.path.dirname(os.path.dirname(__file__))
    config_dir = os.path.abspath(dir_name)
    global _flag
    if not _flag:
        with open(os.path.join(config_dir, "%s" % environ), "r") as f:
            _flag = f.read()
            if _flag:
                _flag = json.loads(_flag)
            else:
                _flag = {}
    return _flag


# token加密
class Aescrypt():
    def __init__(self, key, model, iv, encode_):
        self.encode_ = encode_
        self.model = {'ECB': AES.MODE_ECB, 'CBC': AES.MODE_CBC}[model]
        self.key = self.add_16(key)
        if model == 'ECB':
            self.aes = AES.new(self.key, self.model)
        elif model == 'CBC':
            self.aes = AES.new(self.key, self.model, iv)

    def add_16(self, par):
        par = par.encode(self.encode_)
        while len(par) % 32 != 0:
            par += b'\x00'
        return par

    def aesencrypt(self, text):
        text = self.add_16(text)
        self.encrypt_text = self.aes.encrypt(text)
        return base64.encodebytes(self.encrypt_text).decode().strip()

    def aesdecrypt(self, text):
        text = base64.decodebytes(text.encode(self.encode_))
        self.decrypt_text = self.aes.decrypt(text)
        return self.decrypt_text.decode(self.encode_).strip('\0')


PrAes = Aescrypt('yf7232275', 'ECB', '', 'gbk')
