/**************************************************************************
 OmegaT - Computer Assisted Translation (CAT) tool
          with fuzzy matching, translation memory, keyword search,
          glossaries, and translation leveraging into updated projects.

 Copyright (C) 2012 Martin Fleurke
               2013 Alex Buloichik (alex73mail@gmail.com)
               2015 Thomas Cordonnier
               Home page: http://www.omegat.org/
               Support center: http://groups.yahoo.com/group/OmegaT/

 This file is part of OmegaT.

 OmegaT 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 3 of the License, or
 (at your option) any later version.

 OmegaT 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, see <http://www.gnu.org/licenses/>.
 **************************************************************************/

package org.omegat.gui.editor.mark;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.event.DocumentEvent;
import javax.swing.text.AttributeSet;
import javax.swing.text.Highlighter.HighlightPainter;

import org.omegat.gui.editor.Document3;
import org.omegat.gui.editor.MarkerController;
import org.omegat.core.Core;
import org.omegat.core.data.SourceTextEntry;

/**
 * Abstract marker class that marks source and target text according to some
 * 'pattern' and paints them accoriding to some 'PAINTER' and 'ATTRIBUTES' (all
 * of they defined by implementing classes)
 * 
 * @author Martin Fleurke
 * @author Alex Buloichik (alex73mail@gmail.com)
 */
public abstract class RegexMarker implements IFastMarker {
    protected HighlightPainter PAINTER;
    protected String toolTip;
    protected AttributeSet ATTRIBUTES;
    /** Regexp for mark. */
    protected Pattern pattern;

    public RegexMarker() throws Exception {
    }

    /**
     * Is the marker enabled?
     * 
     * @return true when enabled (markers are painted). false when disabled (no
     *         markers painted)
     */
    protected abstract boolean isEnabled();

    @Override
    public List<Mark> getMarksForEntry(SourceTextEntry ste, String sourceText, String translationText, boolean isActive)
            throws Exception {

        if (!isEnabled()) {
            return null;
        }

        List<Mark> r = new ArrayList<Mark>();
        Matcher match;
        if (isActive || Core.getEditor().getSettings().isDisplaySegmentSources() || translationText == null) {// TODO
            initDrawers(true, isActive);
            if (pattern != null) {
                match = pattern.matcher(sourceText);
                while (match.find()) {
                    Mark m = new Mark(Mark.ENTRY_PART.SOURCE, match.start(), match.end());
                    m.painter = PAINTER;
                    m.toolTipText = toolTip;
                    m.attributes = ATTRIBUTES;
                    r.add(m);
                }
            }
        }
        if (translationText != null) {
            initDrawers(false, isActive);
            if (pattern != null) {
                match = pattern.matcher(translationText);
                while (match.find()) {
                    Mark m = new Mark(Mark.ENTRY_PART.TRANSLATION, match.start(), match.end());
                    m.painter = PAINTER;
                    m.toolTipText = toolTip;
                    m.attributes = ATTRIBUTES;
                    r.add(m);
                }
            }
        }

        return r;
    }

    /**
     * Marker can override this method for define different PAINTER, ATTRIBUTES
     * and PATTERN, based on source/translation, active/inactive and other.
     */
    protected void initDrawers(boolean isSource, boolean isActive) {
    }
    
    public List<MarkerController.MarkInfo> toRemove (DocumentEvent ev, List<MarkerController.MarkInfo> oriList) {
        if (pattern == null) return java.util.Collections.EMPTY_LIST; // avoid exception
        if (!isEnabled()) return java.util.Collections.EMPTY_LIST;
        initDrawers(false, true); // target, active
        
        List<MarkerController.MarkInfo> res = new ArrayList<MarkerController.MarkInfo> (oriList.size());
        for (MarkerController.MarkInfo ori: oriList)
            if (ori.highlight != null)
                if (ori.highlight.getEndOffset() < ev.getOffset()) continue;
                else if ((ev.getType() == DocumentEvent.EventType.INSERT) && (ori.highlight.getStartOffset() > ev.getOffset() + ev.getLength())) continue;
                else if ((ev.getType() == DocumentEvent.EventType.REMOVE) && (ori.highlight.getStartOffset() > ev.getOffset())) continue;
                else res.add (ori);
        return res;
    }
    
    public List<Mark> toAdd (DocumentEvent ev) throws Exception {
        if (pattern == null) return java.util.Collections.EMPTY_LIST; // avoid exception
        if (!isEnabled()) return java.util.Collections.EMPTY_LIST;
        initDrawers(false, true); // target, active

        List<Mark> res = new ArrayList<Mark> ();
        // Contrairly to char marker, we must scan full text because a pattern may start before or end after the selected text
        Document3 doc = (Document3) ev.getDocument();
        String translationText = doc.getText(doc.getTranslationStart(), doc.getTranslationEnd() - doc.getTranslationStart());
        Matcher match = pattern.matcher(translationText); 
        while (match.find()) {
            if (match.end() < ev.getOffset() - doc.getTranslationStart()) continue;
            if (match.start() > ev.getOffset() + ev.getLength() - doc.getTranslationStart()) continue;
            
            Mark m = new Mark(Mark.ENTRY_PART.TRANSLATION, match.start(), match.end());
            m.painter = PAINTER;
            m.toolTipText = toolTip;
            m.attributes = ATTRIBUTES;
            res.add(m);
        }
        return res;
    }
    
    public List<MarkerController.MarkInfo> toRemove (String newTra, List<MarkerController.MarkInfo> oriList) {
        if (pattern == null) return java.util.Collections.EMPTY_LIST; // avoid exception
        if (!isEnabled()) return java.util.Collections.EMPTY_LIST;
        initDrawers(false, true); // target, active
        
        List<MarkerController.MarkInfo> res = new ArrayList<MarkerController.MarkInfo> (oriList.size() / 2 + 1);
        for (MarkerController.MarkInfo ori: oriList)
            if (ori.highlight != null)
                if ( ori.highlight.getStartOffset() == ori.highlight.getEndOffset() )
                    res.add (ori);
        return res;
    }
    
    public List<Mark> toAdd (String newTra) throws Exception {
        if (pattern == null) return java.util.Collections.EMPTY_LIST; // avoid exception
        if (!isEnabled()) return java.util.Collections.EMPTY_LIST;
        initDrawers(false, true); // target, active

        List<Mark> res = new ArrayList<Mark> ();
        Matcher match = pattern.matcher(newTra); 
        while (match.find()) {
            Mark m = new Mark(Mark.ENTRY_PART.TRANSLATION, match.start(), match.end());
            m.painter = PAINTER;
            m.toolTipText = toolTip;
            m.attributes = ATTRIBUTES;
            res.add(m);
        }
        return res;
    }		
    
}
