# hgrcutils.py - Functions to manipulate hgrc (or similar) files
#
# Copyright 2011 Angel Ezquerra <angel.ezquerra@gmail.com>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.

from __future__ import annotations

import os
import typing

from tortoisehg.hgqt import qtlib
from tortoisehg.util import wconfig
from tortoisehg.util.i18n import _

if typing.TYPE_CHECKING:
    from typing import (
        List,
        Optional,
        Tuple,
    )
    from tortoisehg.util.typelib import (
        IniConfig,
    )
    from tortoisehg.hgqt.qtgui import (
        QWidget,
    )

def loadIniFile(rcpath: List[bytes],
                parent: Optional[QWidget] = None) -> Tuple[Optional[bytes], IniConfig]:
    for fn in rcpath:
        if os.path.exists(fn):
            break
    else:
        for fn in rcpath:
            # Try to create a file from rcpath
            try:
                with open(fn, 'w') as f:
                    f.write('# Generated by TortoiseHg\n')
                break
            except OSError:
                pass
        else:
            qtlib.WarningMsgBox(_('Unable to create a config file'),
                   _('Insufficient access rights.'), parent=parent)
            return None, wconfig.config()

    return fn, wconfig.readfile(fn)

def setConfigValue(rcfilepath: bytes, cfgpath: bytes, value: bytes) -> bool:
    '''
    Set a value on a config file, such as an hgrc or a .ini file

    rcpfilepath: Absolute path to a configuration file
    cfgpath: Full "path" of a configurable key
             Format is section.keyNamee.g. 'web.name')
    value: String value for the selected config key
    '''
    fn, cfg = loadIniFile([rcfilepath])
    if not hasattr(cfg, 'write'):
        return False
    if fn is None:
        return False
    cfgFullKey = cfgpath.split(b'.')
    if len(cfgFullKey) < 2:
        return False
    cfg.set(cfgFullKey[0], cfgFullKey[1], value)
    try:
        wconfig.writefile(cfg, fn)
    except OSError as e:
        return False
    return True
