using System ;
using System.Text ;
using System.Security ;
using System.Windows.Forms ;
using System.Collections.Generic ;

using log4net ;

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

public static partial class Program
{

    private class MyMessageFilter : IMessageFilter {
        public bool PreFilterMessage( ref Message msg ) {
            // check if we should filter this message
            if ( Program.mainForm.preFilterMessage( ref msg ) )
                return true ;
            return false ;
        }
    }

    private static void loadPredefinedSearchQueries( string fname )
    {
        // load the pre-defined search queries
        JsonConfig jsonConfig = new JsonConfig( "pre-defined search queries", fname ) ;
        ILog logger = LogManager.GetLogger( "shortcuts" ) ;
        foreach( dynamic entry in jsonConfig.data ) {
            string queryString = entry["query"] ?? "" ;
            if ( queryString == "" ) {
                Program.logStartupMsg( "bad-shortcut", $"{entry["shortcut"]}: Missing query string" ) ;
                continue ;
            }
            string shortcutString = entry["shortcut"] ?? "" ;
            Keys? keys = Shortcut.parseShortcutString( (string) shortcutString ) ;
            if ( keys == null ) {
                Program.logStartupMsg( "bad-shortcut", $"{queryString}: {shortcutString}" ) ;
                continue ;
            }
            Shortcut shortcut = new SearchQueryShortcut( keys.Value, queryString ) ;
            logger.Info( $"Registering search query shortcut: {shortcut} => {queryString}" ) ;
            Shortcut.registerShortcut( shortcut ) ;
        }
    }

    public static void logStartupMsg( string key, string msg )
    {
        // log the startup message
        List<string> msgs ;
        if ( ! mStartupMsgs.TryGetValue( key, out msgs ) )
            mStartupMsgs[key] = msgs = new List<string>() ;
        msgs.Add( msg ) ;
    }

    public static string getStartupMsgs( string key, string caption )
    {
        // check if there were any startup messages of the specified type
        List<string> msgs ;
        if ( ! mStartupMsgs.TryGetValue( key, out msgs ) || msgs.Count == 0 )
            return "" ;

        // NOTE: WebBrowser isn't really available with Mono, so we just log startup messages normally.
        ILog logger = LogManager.GetLogger( "startup" ) ;

        // generate a report for the specified startup messages
        StringBuilder buf = new StringBuilder() ;
        if ( caption != "" ) {
            buf.Append( caption ) ;
            logger.Warn( caption ) ;
        }
        buf.Append( "<ul>" ) ;
        foreach ( string msg in msgs ) {
            buf.Append( "<li> " + SecurityElement.Escape(msg) ) ;
            logger.Warn( (caption != "") ? $"- {msg}" : msg ) ;
        }
        buf.Append( "</ul>" ) ;

        return buf.ToString() ;
    }

}
