/*
 *  PHEX - The pure-java Gnutella-servent.
 *  Copyright (C) 2001 - 2006 Phex Development Group
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 * 
 *  Created on 
 *  --- CVS Information ---
 *  $Id: SearchFilterRules.java 3442 2006-06-16 19:05:30Z gregork $
 */
package phex.rules;

import java.io.File;
import java.io.IOException;
import java.util.*;

import phex.common.Environment;
import phex.common.ThreadPool;
import phex.common.file.FileManager;
import phex.common.file.ManagedFile;
import phex.common.file.ManagedFileException;
import phex.connection.NetworkManager;
import phex.event.UserMessageListener;
import phex.rules.condition.AndConcatCondition;
import phex.rules.condition.Condition;
import phex.rules.consequence.Consequence;
import phex.utils.NLogger;
import phex.utils.NLoggerNames;
import phex.utils.VersionUtils;
import phex.xml.sax.*;
import phex.xml.sax.parser.rules.SearchRuleListHandler;
import phex.xml.sax.rules.*;

public class SearchFilterRules
{
    private boolean hasChangedSinceLastSave;

    private List searchFilterRules;

    public SearchFilterRules()
    {
        searchFilterRules = new ArrayList();
        searchFilterRules.add( DefaultSearchFilterRules.ADULT_FILTER_RULE );
        searchFilterRules.add( DefaultSearchFilterRules.SCAM_FILE_FILTER_RULE ); 
        hasChangedSinceLastSave = false;

        Environment.getInstance().scheduleTimerTask( new SaveFavoritesTimer(),
            SaveFavoritesTimer.TIMER_PERIOD, SaveFavoritesTimer.TIMER_PERIOD );
    }

    /**
     * Sets the rule list.
     * @param newList
     */
    public synchronized void setRuleList( List newList )
    {
        searchFilterRules = newList;
        hasChangedSinceLastSave = true;
    }

    /**
     * Returns a unmodifiable list of search rules.
     * @return
     */
    public synchronized List getAsList()
    {
        return Collections.unmodifiableList( searchFilterRules );
    }
    
    /**
     * Returns a unmodifiable list of search rules.
     * @return
     */
    public synchronized List getPermanentList()
    {
        List list = new ArrayList();
        Iterator iterator = searchFilterRules.iterator();
        while ( iterator.hasNext() )
        {
            Rule rule = (Rule) iterator.next();
            if ( rule.isPermanentlyEnabled() )
            {
                list.add(rule);
            }
        }
        return list;
    }

    /**
     * Returns the number of available search filters.
     * @return the number of available search filters.
     */
    public synchronized int getCount()
    {
        return searchFilterRules.size();
    }

    /**
     * Returns the search filter at index.
     * @param index the index
     * @return the search filter at index.
     */
    public synchronized Rule getRuleAt( int index )
    {
        if ( index < 0 || index >= searchFilterRules.size() )
        {
            return null;
        }
        return (Rule) searchFilterRules.get( index );
    }
    
    /**
     * Returns the search filter with given id.
     * @param id the id
     * @return the search filter with id or null if not found.
     */
    public synchronized Rule getRuleById( String id )
    {
        Iterator iterator = searchFilterRules.iterator();
        while ( iterator.hasNext() )
        {
            Rule rule = (Rule) iterator.next();
            if ( id.equals( rule.getId() ) )
            {
                return rule;
            }
        }
        return null;
    }

    public synchronized void save()
    {
        if ( !hasChangedSinceLastSave )
        {
            return;
        }

        NLogger.debug( SearchFilterRules.class, "Saving search filters." );
        try
        {
            DPhex dPhex = new DPhex();
            dPhex.setPhexVersion( VersionUtils.getFullProgramVersion() );

            DSubElementList dList = new DSubElementList(
                SearchRuleListHandler.THIS_TAG_NAME );
            dPhex.setSearchRuleList( dList );

            List searchRuleList = dList.getSubElementList();
            Iterator iterator = searchFilterRules.iterator();
            while ( iterator.hasNext() )
            {
                Rule rule = (Rule) iterator.next();
                
                DSearchRule dRule = new DSearchRule();
                dRule.setId( rule.getId() );
                dRule.setName( rule.getName() );
                dRule.setDescription( rule.getDescription() );
                dRule.setPermanentlyEnabled( rule.isPermanentlyEnabled() );

                DAndConcatCondition andCondition = new DAndConcatCondition();
                List dCondList = andCondition.getSubElementList();
                Iterator condIterator = rule.getConditions().iterator();
                while ( condIterator.hasNext() )
                {
                    Condition cond = (Condition) condIterator.next();
                    DElement dCond = cond.createDCondition();
                    dCondList.add( dCond );
                }
                dRule.setAndConcatCondition( andCondition );

                DConsequencesList dConsequ = new DConsequencesList();
                List dConsequList = dConsequ.getSubElementList();
                Iterator consequIterator = rule.getConsequences().iterator();
                while ( consequIterator.hasNext() )
                {
                    Consequence consqu = (Consequence) consequIterator.next();
                    DElement dCond = consqu.createDConsequence();
                    dConsequList.add( dCond );
                }
                dRule.setConsequencesList( dConsequ );

                searchRuleList.add( dRule );
            }

            NetworkManager networkMgr = NetworkManager.getInstance();
            File outputFile = networkMgr.getGnutellaNetwork()
                .getSearchFilterFile();
            ManagedFile managedFile = FileManager.getInstance()
                .getReadWriteManagedFile( outputFile );
            XMLBuilder.saveToFile( managedFile, dPhex );
            hasChangedSinceLastSave = false;
        }
        catch (IOException exp)
        {
            // TODO during close this message is never displayed since application
            // will exit too fast. A solution to delay exit process in case 
            // SlideInWindows are open needs to be found.
            NLogger.error( NLoggerNames.Favorites, exp, exp );
            Environment.getInstance().fireDisplayUserMessage(
                UserMessageListener.FavoritesSettingsSaveFailed, new String[]
                { exp.toString() } );
        }
        catch (ManagedFileException exp)
        {
            // TODO during close this message is never displayed since application
            // will exit too fast. A solution to delay exit process in case 
            // SlideInWindows are open needs to be found.
            NLogger.error( NLoggerNames.Favorites, exp, exp );
            Environment.getInstance().fireDisplayUserMessage(
                UserMessageListener.FavoritesSettingsSaveFailed, new String[]
                { exp.toString() } );
        }
    }

    public synchronized void load()
    {
        NLogger.debug( SearchFilterRules.class, "Loading search filters." );

        NetworkManager networkMgr = NetworkManager.getInstance();
        File inputFile = networkMgr.getGnutellaNetwork().getSearchFilterFile();

        DPhex dPhex;
        try
        {
            if ( !inputFile.exists() )
            {
                return;
            }
            FileManager fileMgr = FileManager.getInstance();
            ManagedFile managedFile = fileMgr
                .getReadWriteManagedFile( inputFile );
            dPhex = XMLBuilder.loadDPhexFromFile( managedFile );
            if ( dPhex == null )
            {
                NLogger.debug( NLoggerNames.Favorites, "No DPhex found." );
                return;
            }
            DSubElementList dRuleList = dPhex.getSearchRuleList();
            if ( dRuleList == null )
            {
                NLogger.warn( NLoggerNames.Favorites,
                    "No DSearchRule list found." );
            }

            List newRules = new ArrayList();
            Iterator iterator = dRuleList.getSubElementList().iterator();
            while ( iterator.hasNext() )
            {
                DSearchRule dRule = (DSearchRule) iterator.next();

                Rule rule = null;
                boolean isNew = false;
                String id = dRule.getId();
                if ( id != null )
                {
                    // try to find existing.
                    rule = getRuleById( id );
                }
                if ( rule == null )
                {
                    isNew = true;
                    rule = new Rule();
                }
                
                if ( !rule.isDefaultRule() )
                {
                    String name = dRule.getName();
                    rule.setName( name );
    
                    DAndConcatCondition dCondition = dRule.getAndConcatCondition();
                    AndConcatCondition andCond = (AndConcatCondition) dCondition
                        .createCondition();
    
                    Iterator conditions = andCond.getConditions().iterator();
                    while ( conditions.hasNext() )
                    {
                        rule.addCondition( (Condition) conditions.next() );
                    }
    
                    DConsequencesList consequencesList = dRule
                        .getConsequencesList();
                    Iterator consequIterator = consequencesList.getSubElementList()
                        .iterator();
                    while ( consequIterator.hasNext() )
                    {
                        DConsequence dConsequ = (DConsequence) consequIterator
                            .next();
                        Consequence conseq = dConsequ.createConsequence();
                        rule.addConsequence( conseq );
                    }
                }
                if ( dRule.isHasPermanentlyEnabled() )
                {
                    rule.setPermanentlyEnabled( dRule.isPermanentlyEnabled() );
                }
                if ( isNew )
                {
                    newRules.add( rule );
                }
            }
            searchFilterRules.addAll(newRules);
        }
        catch (IOException exp)
        {
            NLogger.error( NLoggerNames.Favorites, exp, exp );
            Environment.getInstance().fireDisplayUserMessage(
                UserMessageListener.FavoritesSettingsLoadFailed, new String[]
                { exp.toString() } );
            return;
        }
        catch (ManagedFileException exp)
        {
            NLogger.error( NLoggerNames.Favorites, exp, exp );
            Environment.getInstance().fireDisplayUserMessage(
                UserMessageListener.FavoritesSettingsLoadFailed, new String[]
                { exp.toString() } );
            return;
        }
    }

    ///////////////////// START event handling methods ////////////////////////
    //
    //    /**
    //     * All listeners interested in events.
    //     */
    //    private ArrayList listenerList = new ArrayList( 2 );
    //
    //    public void addSearchFilterListListener( SearchFilterListListener listener )
    //    {
    //        listenerList.add( listener );
    //    }
    //
    //    public void removeSearchListChangeListener( SearchFilterListListener listener )
    //    {
    //        listenerList.remove( listener );
    //    }
    //
    //    protected void fireSearchFilterChanged( final int position )
    //    {
    //        // invoke update in event dispatcher
    //        AsynchronousDispatcher.invokeLater(
    //        new Runnable()
    //        {
    //            public void run()
    //            {
    //                Object[] listeners = listenerList.toArray();
    //                SearchFilterListListener listener;
    //                // Process the listeners last to first, notifying
    //                // those that are interested in this event
    //                for ( int i = listeners.length - 1; i >= 0; i-- )
    //                {
    //                    listener = (SearchFilterListListener)listeners[ i ];
    //                    listener.searchFilterChanged( position );
    //                }
    //            }
    //        });
    //    }
    //
    //    protected void fireSearchFilterAdded( final int position )
    //    {
    //        // invoke update in event dispatcher
    //        AsynchronousDispatcher.invokeLater(
    //        new Runnable()
    //        {
    //            public void run()
    //            {
    //                Object[] listeners = listenerList.toArray();
    //                SearchFilterListListener listener;
    //                // Process the listeners last to first, notifying
    //                // those that are interested in this event
    //                for ( int i = listeners.length - 1; i >= 0; i-- )
    //                {
    //                    listener = (SearchFilterListListener)listeners[ i ];
    //                    listener.searchFilterAdded( position );
    //                }
    //            }
    //        });
    //    }
    //
    //    protected void fireSearchFilterRemoved( final int position )
    //    {
    //        // invoke update in event dispatcher
    //        AsynchronousDispatcher.invokeLater(
    //        new Runnable()
    //        {
    //            public void run()
    //            {
    //                Object[] listeners = listenerList.toArray();
    //                SearchFilterListListener listener;
    //                // Process the listeners last to first, notifying
    //                // those that are interested in this event
    //                for ( int i = listeners.length - 1; i >= 0; i-- )
    //                {
    //                    listener = (SearchFilterListListener)listeners[ i ];
    //                    listener.searchFilterRemoved( position );
    //                }
    //            }
    //        });
    //    }
    //
    //    protected void fireSearchFilterChanged( SearchFilter search )
    //    {
    //        int position = searchFilterRules.indexOf( search );
    //        if ( position >= 0 )
    //        {
    //            fireSearchFilterChanged( position );
    //        }
    //    }
    ///////////////////// END event handling methods ////////////////////////

    ////////////////////// START inner classes //////////////////////////

    private class SaveRunner implements Runnable
    {
        public void run()
        {
            save();
        }
    }

    private class SaveFavoritesTimer extends TimerTask
    {
        // once per minute
        public static final long TIMER_PERIOD = 1000 * 60;

        public void run()
        {
            try
            {
                // trigger the save inside a background job
                ThreadPool.getInstance().addJob( new SaveRunner(),
                    "SaveSearchFilterRules" );
            }
            catch (Throwable th)
            {
                NLogger.error( NLoggerNames.Favorites, th, th );
            }
        }
    }
}
