from core.Constants import Constants from dataclasses import dataclass from dataclasses_json import dataclass_json from json import JSONDecodeError from pathlib import Path import json import os import pathlib @dataclass_json @dataclass class SystemState: profile_id: int @staticmethod def get(): try: system_state_file_contents = open(SystemState._get_state_path() + '/system.json', 'r').read() except FileNotFoundError: return None try: system_state = json.loads(system_state_file_contents) except JSONDecodeError: return None # noinspection PyUnresolvedReferences return SystemState.from_dict(system_state) @staticmethod def exists(): return os.path.isfile(SystemState._get_state_path() + '/system.json') @staticmethod def save(system_state): system_state_file_contents = system_state.to_json(indent=4) + '\n' os.makedirs(SystemState._get_state_path(), exist_ok=True, mode=0o700) system_state_file_path = SystemState._get_state_path() + '/system.json' Path(system_state_file_path).touch(exist_ok=True, mode=0o600) text_io_wrapper = open(system_state_file_path, 'w') text_io_wrapper.write(system_state_file_contents) @staticmethod def dissolve(): system_state = SystemState.get() if system_state is not None: system_state_path = SystemState._get_state_path() + '/system.json' pathlib.Path.unlink(Path(system_state_path), missing_ok=True) @staticmethod def _get_state_path(): return Constants.SP_STATE_HOME