# 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.

import os

from tortoisehg.hgqt import qtlib
from tortoisehg.util import wconfig
from tortoisehg.util.i18n import _
from tortoisehg.util import (
    hglib,
)

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

def loadIniFile(rcpath, parent=None):
    # type: (List[bytes], Optional[QWidget]) -> 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 EnvironmentError:
                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, cfgpath, value):
    # type: (bytes, bytes, 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 EnvironmentError as e:
        return False
    return True
