# Copyright (C) 2022 The Qt Company Ltd.
# SPDX-License-Identifier: LicenseRef-Qt-Commercial

import json
import os
from typing import List, Optional
import warnings

from PySide6.QtCore import QStandardPaths

_option_creator_path = ''
_option_use_creator = False
_option_recent_files: List[str] = []


def _settings_file_name() -> str:
    path = QStandardPaths.writableLocation(QStandardPaths.ConfigLocation)
    return f'{path}/shibokenwizardconfig.json'


def _load_options_dict() -> Optional[dict]:
    """Load the serialized options from the settings file"""
    result = None
    file_name = _settings_file_name()
    if os.path.isfile(file_name):
        with open(file_name, 'r') as f:
            result = json.load(f)
    return result


def _load_options() -> None:
    """Load options"""
    global _option_use_creator, _option_creator_path, _option_recent_files
    data = _load_options_dict()
    if data:
        _option_use_creator = data.get('UseQtCreator', False)
        _option_creator_path = data.get('QtCreator', '')
        _option_recent_files = data.get('RecentFiles', [])


def _save_options() -> None:
    """Save options if they have changed comparing to the current
       options file."""
    global _option_use_creator, _option_creator_path, _option_recent_files
    data = {'UseQtCreator': _option_use_creator,
            'QtCreator': _option_creator_path,
            'RecentFiles': _option_recent_files}
    if data != _load_options_dict():
        with open(_settings_file_name(), 'w') as f:
            json.dump(data, f)


class Options:
    """Class with static methods for accessing options"""

    @staticmethod
    def use_creator() -> bool:
        global _option_use_creator
        return _option_use_creator

    @staticmethod
    def set_use_creator(u: bool) -> None:
        global _option_use_creator
        _option_use_creator = u

    @staticmethod
    def creator_path() -> str:
        global _option_creator_path
        return _option_creator_path

    @staticmethod
    def set_creator_path(p: str) -> None:
        global _option_creator_path
        _option_creator_path = p

    @staticmethod
    def recent_files() -> List[str]:
        global _option_recent_files
        return _option_recent_files

    @staticmethod
    def set_recent_files(f: List[str]) -> None:
        global _option_recent_files
        _option_recent_files = f

    @staticmethod
    def load_options() -> None:
        """Load options at startup"""
        try:
            _load_options()
        except:  # noqa: E722
            pass

    @staticmethod
    def save_options() -> None:
        try:
            _save_options()
        except Exception as e:
            reason = str(e)
            warnings.warn(f'Unable to save settings {reason}')
