//   Copyright 2012 Georg-August-Universität Göttingen, Germany
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

package de.ugoe.cs.autoquest.tasktrees.temporalrelation;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.HashMap;

import de.ugoe.cs.autoquest.eventcore.IEventType;
import de.ugoe.cs.autoquest.tasktrees.taskequality.TaskEquality;
import de.ugoe.cs.autoquest.tasktrees.taskequality.TaskEqualityRuleManager;
import de.ugoe.cs.autoquest.tasktrees.treeifc.IEventTask;
import de.ugoe.cs.autoquest.tasktrees.treeifc.IIteration;
import de.ugoe.cs.autoquest.tasktrees.treeifc.ISelection;
import de.ugoe.cs.autoquest.tasktrees.treeifc.ISequence;
import de.ugoe.cs.autoquest.tasktrees.treeifc.ITask;
import de.ugoe.cs.autoquest.tasktrees.treeifc.ITaskInstance;
import de.ugoe.cs.autoquest.usageprofiles.SymbolComparator;

/**
 * TODO comment
 */
class TaskComparator implements SymbolComparator<ITaskInstance> {
    
    /**  */
    private static final long serialVersionUID = 1L;
    
    /** */
    private static final int MAX_BUFFER_SIZE = 10 * 1024 * 1024;

    /** */
    private TaskEquality minimalNodeEquality;

    /** */
    private transient Comparer comparer;

    /** */
    private transient Comparer lexicalComparer;

    /** */
    private transient HashMap<Long, Boolean> equalityBuffer = new HashMap<Long, Boolean>();

    /** */
    private transient HashMap<Long, Boolean> lexicalEqualityBuffer;

    /**
     *
     */
    public TaskComparator(TaskEquality minimalNodeEquality) {
        this.minimalNodeEquality = minimalNodeEquality;
        init();
    }

    /* (non-Javadoc)
     * @see SymbolComparator#equals(Object, Object)
     */
    @Override
    public boolean equals(ITaskInstance taskInstance1, ITaskInstance taskInstance2) {
        return equals(taskInstance1.getTask(), taskInstance2.getTask());
    }        

    /**
     * 
     */
    public boolean equals(ITask task1, ITask task2) {
        Boolean result;
        
        if (task1 != task2) {
            if ((task1 instanceof IEventTask) && (task2 instanceof IEventTask)) {
                long key = ((long) System.identityHashCode(task1)) << 32;
                key += System.identityHashCode(task2);
            
                result = equalityBuffer.get(key);
            
                if (result == null) {
                    result = comparer.compare(task1, task2);
                    
                    if (equalityBuffer.size() < MAX_BUFFER_SIZE) {
                        equalityBuffer.put(key, result);
                    }
                }
            }
            else {
                result = false;
            }
        }
        else {
            result = true;
        }
        
        return result;
    }

    /**
     *
     */
    public boolean areLexicallyEqual(ITask task1, ITask task2) {
        Boolean result;
        
        if (task1 != task2) {
            long key = ((long) System.identityHashCode(task1)) << 32;
            key += System.identityHashCode(task2);
            
            result = lexicalEqualityBuffer.get(key);
            
            if (result == null) {
                result = lexicalComparer.compare(task1, task2);
                if (equalityBuffer.size() < 1024 * 1024 * 10) {
                    lexicalEqualityBuffer.put(key, result);
                }
            }
        }
        else {
            result = true;
        }
        
        return result;
    }
    
    /* (non-Javadoc)
     * @see SymbolComparator#getBucketSearchOrder(Object)
     */
    @Override
    public int[] getBucketSearchOrder(ITaskInstance taskInstance) {
        // 0 = sequence; 1 = selection; 2 = iteration; 3 = optional; 4 = event task in general;
        // other = hashCode of name of event type
        
        ITask task = taskInstance.getTask();
        
        if (task instanceof IEventTask) {
            // event tasks are most likely equal to those of the event type with the same name,
            // Afterwards, they may be equal to iterations, optionals, other event tasks,
            // selections, and finally the rest.
            IEventType eventType = ((IEventTask) task).getEventType();
            return new int[] { eventType.getName().hashCode(), 2, 3, 4, 1 };                       
        }
        else if (task instanceof ISequence) {
            return new int[] { 0, 2, 3, 1 };                       
        }
        else if (task instanceof ISelection) {
            return new int[] { 1, 4, 2, 3 };                       
        }
        else if (task instanceof IIteration) {
            return new int[] { 2, 1, 4 };                       
        }
        
        return null;
    }

    /**
     * 
     */
    private void init() {
        if (minimalNodeEquality == TaskEquality.LEXICALLY_EQUAL) {
            comparer = new LexicalComparer();
        }
        else if (minimalNodeEquality == TaskEquality.SYNTACTICALLY_EQUAL) {
            comparer = new SyntacticalComparer();
        }
        else if (minimalNodeEquality == TaskEquality.SEMANTICALLY_EQUAL) {
            comparer = new SemanticalComparer();
        }
        else {
            comparer = new DefaultComparer(this.minimalNodeEquality);
        }
        
        if (minimalNodeEquality == TaskEquality.LEXICALLY_EQUAL) {
            lexicalComparer = comparer;
            lexicalEqualityBuffer = equalityBuffer;
        }
        else {
            lexicalComparer = new LexicalComparer();
            lexicalEqualityBuffer = new HashMap<Long, Boolean>();
        }
    }
    
    /**
     * <p>
     * deserialize this object and reinitialize the buffers
     * </p>
     */
    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
        in.defaultReadObject();
        init();
    }


    /**
     * 
     */
    private static interface Comparer {
        
        /**
         * 
         */
        boolean compare(ITask task1, ITask task2);
    }

    /**
     * 
     */
    private static class LexicalComparer implements Comparer {
        
        /**
         * 
         */
        public boolean compare(ITask task1, ITask task2) {
            return TaskEqualityRuleManager.getInstance().areLexicallyEqual(task1, task2);
        }
    }

    /**
     * 
     */
    private static class SyntacticalComparer implements Comparer {
        
        /**
         * 
         */
        public boolean compare(ITask task1, ITask task2) {
            return TaskEqualityRuleManager.getInstance().areSyntacticallyEqual(task1, task2);
        }
    }

    /**
     * 
     */
    private static class SemanticalComparer implements Comparer {
        
        /**
         * 
         */
        public boolean compare(ITask task1, ITask task2) {
            return TaskEqualityRuleManager.getInstance().areSemanticallyEqual(task1, task2);
        }
    }

    /**
     * 
     */
    private static class DefaultComparer implements Comparer {
        
        /**
         * <p>
         * the minimal task equality two identified sublists need to have to consider them as equal
         * </p>
         */
        private TaskEquality minimalNodeEquality;
        
        /**
         *
         */
        public DefaultComparer(TaskEquality minimalNodeEquality) {
           this.minimalNodeEquality = minimalNodeEquality;
        }
        
        /**
         * 
         */
        public boolean compare(ITask task1, ITask task2) {
            return TaskEqualityRuleManager.getInstance().areAtLeastEqual
                (task1, task2, minimalNodeEquality);
        }
    }
}