/*
 * File:     Replace.java
 * Project:  MPI Linguistic Application
 * Date:     03 April 2006
 *
 * Copyright (C) 2001-2006  Max Planck Institute for Psycholinguistics
 *
 * 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
 */

package mpi.eudico.client.annotator.search.result.model;

import mpi.eudico.server.corpora.clomimpl.abstr.TranscriptionImpl;

import mpi.search.content.result.model.ContentResult;


/**
 * @author klasal
 *
 * TODO To change the template for this generated type comment go to Window -
 * Preferences - Java - Code Style - Code Templates
 */
public class Replace {
    static public void execute(ContentResult result, String string) {
        execute(result, string, null);
    }

    static public void execute(ContentResult result, String string,
        TranscriptionImpl transcription) {
        if (transcription != null) {
            transcription.setNotifying(false);
        }

        for (int i = 1; i <= result.getMatchCount(); i++) {
            ElanMatch match = (ElanMatch) result.getMatch(i);
            String oldString = match.getAnnotation().getValue();
            int[][] locations = match.getMatchedSubstringIndices();

            if (locations.length > 0) {
                try {
                    StringBuffer sb = new StringBuffer();
                    sb.append(oldString.substring(0, locations[0][0]));
                    sb.append(string);

                    for (int j = 0; j < (locations.length - 1); j++) {
                        sb.append(oldString.substring(locations[j][1],
                                locations[j + 1][0]));
                        sb.append(string);
                    }

                    sb.append(oldString.substring(
                            locations[locations.length - 1][1],
                            oldString.length()));
                    match.getAnnotation().setValue(sb.toString());

                    // erase matchIndices
                    match.setMatchedSubstringIndices(new int[0][0]);
                } catch (StringIndexOutOfBoundsException e) {
                    System.out.println("Warning: " + e.getMessage());
                }
            }
        }

        if (transcription != null) {
            transcription.setNotifying(true);
        }
    }
}
