using System ;
using System.IO ;

using Newtonsoft.Json ;
using Newtonsoft.Json.Linq ;
using log4net ;

// --------------------------------------------------------------------

public class JsonConfig
{
    private string mFilename ;
    private dynamic mData ;

    public JsonConfig( string caption, string fname )
    {
        // initialize
        ILog logger = LogManager.GetLogger( "startup" ) ;
        mFilename = fname ;

        // load the JSON config
        string data ;
        if ( File.Exists( fname ) ) {
            logger.Info( $"Loading {caption}: {Path.GetFullPath(fname)}" ) ;
            data = File.ReadAllText( fname ) ;
        } else
            data ="{}" ;
        mData = JsonConvert.DeserializeObject( data ) ;
        logger.Debug( mData.ToString() ) ;
    }

    public string getStringVal( string[] keys, string defaultVal="" )
    {
        // get the specified value
        JToken curr = mData ;
        foreach( string key in keys ) {
            curr = curr[ key ] ;
            if ( curr == null )
                return defaultVal ;
        }
        return (string) curr ;
    }
    public void setStringVal( string[] keys, string val, bool save=true ) { setVal( keys, val, save ) ; }

    public int getIntVal( string[] keys, int defaultVal=0 )
    {
        // get the specified value
        string val = getStringVal( keys ) ;
        try {
            return Int32.Parse( val ) ;
        } catch( FormatException ) {
            return defaultVal ;
        }
    }
    public void setIntVal( string[] keys, int val, bool save=true ) { setVal( keys, val, save ) ; }

    public float getFloatVal( string[] keys, float defaultVal=0 )
    {
        // get the specified value
        string val = getStringVal( keys ) ;
        try {
            return float.Parse( val ) ;
        } catch( FormatException ) {
            return defaultVal ;
        }
    }

    private void setVal( string[] keys, dynamic val, bool save )
    {
        // set the specified value
        JToken curr = mData ;
        for ( int i=0 ; i < keys.Length-1 ; ++i ) {
            if ( curr[ keys[i] ] == null )
                curr[ keys[i] ] = (JToken) JsonConvert.DeserializeObject( "{}" ) ;
            curr = curr[ keys[i] ] ;
        }
        curr[ keys[keys.Length-1] ] = val ;

        // save the updated config
        if ( save )
            File.WriteAllText( mFilename, data.ToString() ) ;
    }

    public dynamic data { get { return mData ; } }
}
