import json as _json
import os as _os
import io as _io
import typing as _typing

def mandarinCode(text: str):
    res = []
    for c in text:
        res.append(str(ord(c)))
    return 'm'.join(res)
def unMandarinCode(mdrCode: str):
    chrs = mdrCode.split("m")
    res = ''
    for c in chrs:
        res += chr(int(c))
    return res

class MandarinJson:
    def __init__(self):
        self.filename: str = None
    def load(self, filename: str) -> _typing.NoReturn:
        if self.filename:
            raise MandarinError("File is already loaded.")
        self.filename = filename
    def write(self, data: dict, mode: _typing.Literal['w', 'a'] = 'w') -> _io.TextIOWrapper:
        if not self.filename:
            raise MandarinError("Please, load a file.")
        textData = mandarinCode(_json.dumps(data))
        tempFile = open(self.filename, mode)
        tempFile.write(textData)
        tempFile.close()
    def close(self) -> _typing.NoReturn:
        if not self.filename:
            raise MandarinError("Please, load a file.")
        self.filename = None
    def read(self) -> dict:
        if not self.filename:
            raise MandarinError("Please, load a file.")
        tempFile = open(self.filename, 'r')
        text = unMandarinCode(tempFile.read())
        tempFile.close()
        return _json.loads(text)
class MandarinData:
    def __init__(self):
        self.filename: str = None
    def load(self, filename: str) -> _typing.NoReturn:
        if self.filename:
            raise MandarinError("File is already loaded.")
        self.filename = filename
    def write(self, data: dict, mode: _typing.Literal['w', 'a'] = 'w') -> _io.TextIOWrapper:
        if not self.filename:
            raise MandarinError("Please, load a file.")
        hexData = data.encode('utf-8').hex()
        tempFile = open(self.filename, mode)
        tempFile.write(hexData)
        tempFile.close()
    def close(self) -> _typing.NoReturn:
        if not self.filename:
            raise MandarinError("Please, load a file.")
        self.filename = None
    def read(self) -> dict:
        if not self.filename:
            raise MandarinError("Please, load a file.")
        tempFile = open(self.filename, 'r')
        text = bytes.fromhex(tempFile.read())
        text = text.decode()
        tempFile.close()
        return text

class MandarinError(Exception):
    def __init__(self, msg):
        super().__init__(msg)
