/* LanguageTool, a natural language style checker 
 * Copyright (C) 2005 Daniel Naber (http://www.danielnaber.de)
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301
 * USA
 */
package org.languagetool.rules;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;

import org.languagetool.AnalyzedSentence;
import org.languagetool.AnalyzedTokenReadings;
import org.languagetool.JLanguageTool;
import org.languagetool.tools.StringTools;

/**
 * A rule that matches words or phrases which should not be used and suggests
 * correct ones instead. Loads the relevant words  from 
 * <code>rules/XX/replace.txt</code>, where XX is a code of the language.
 * 
 * @author Andriy Rysin
 */
public abstract class AbstractSimpleReplaceRule extends Rule {
  
  private static final String FILE_ENCODING = "utf-8";

  private final Map<String, String> wrongWords; // e.g. "вреѿті реѿт" -> "зреѿтою"

  public abstract String getFileName();
  
  public String getEncoding() {
    return FILE_ENCODING;
  }
  
  /**
   * Indicates if the rule is case-sensitive. Default value is <code>true</code>.
   * @return true if the rule is case-sensitive, false otherwise.
   */
  public boolean isCaseSensitive() {
    return true;  
  }
  
  /**
   * @return the locale used for case conversion when {@link #isCaseSensitive()} is set to <code>false</code>.
   */
  public Locale getLocale() {
    return Locale.getDefault();
  }  
  
  public AbstractSimpleReplaceRule(final ResourceBundle messages) throws IOException {
    if (messages != null) {
      super.setCategory(new Category(messages.getString("category_misc")));
    }
    wrongWords = loadWords(JLanguageTool.getDataBroker().getFromRulesDirAsStream(getFileName()));
  }

  @Override
  public String getId() {
    return "SIMPLE_REPLACE";
  }

  @Override
  public String getDescription() {
    return "Checks for wrong words/phrases";
  }
  
  public String getSuggestion() {
    return " is not valid, use ";
  }
  
  public String getShort() {
    return "Wrong word";
  }

  @Override
  public final RuleMatch[] match(final AnalyzedSentence text) {
    final List<RuleMatch> ruleMatches = new ArrayList<RuleMatch>();
    final AnalyzedTokenReadings[] tokens = text.getTokensWithoutWhitespace();

    for (int i = 1; i < tokens.length; i++) {
      final String token = tokens[i].getToken();

      final String origToken = token;
      final String replacement = isCaseSensitive() ? wrongWords.get(token) : wrongWords.get(token.toLowerCase(getLocale()));
      if (replacement != null) {
    	final String msg = token + getSuggestion() + replacement;
        final int pos = tokens[i].getStartPos();
        final RuleMatch potentialRuleMatch = new RuleMatch(this, pos, pos
            + origToken.length(), msg, getShort());
        if (!isCaseSensitive() && StringTools.startsWithUppercase(token)) {
          potentialRuleMatch.setSuggestedReplacement(StringTools.uppercaseFirstChar(replacement));
        } else {
          potentialRuleMatch.setSuggestedReplacement(replacement);
        }
        ruleMatches.add(potentialRuleMatch);
      }
    }
    return toRuleMatchArray(ruleMatches);
  }


  private Map<String, String> loadWords(final InputStream file) throws IOException {
    final Map<String, String> map = new HashMap<String, String>();
    InputStreamReader isr = null;
    BufferedReader br = null;
    try {
      isr = new InputStreamReader(file, getEncoding());
      br = new BufferedReader(isr);
      String line;

      while ((line = br.readLine()) != null) {
        line = line.trim();
        if (line.length() < 1) {
          continue;
        }
        if (line.charAt(0) == '#') { // ignore comments
          continue;
        }
        final String[] parts = line.split("=");
        if (parts.length != 2) {
          throw new IOException("Format error in file "
              + JLanguageTool.getDataBroker().getFromRulesDirAsUrl(getFileName()) + ", line: " + line);
        }
        map.put(parts[0], parts[1]);
      }

    } finally {
      if (br != null) {
        br.close();
      }
      if (isr != null) {
        isr.close();
      }
    }
    return map;
  }

  @Override
  public void reset() {
  }  
  
}

@@ -891,287 +891,8 @@
 s;%0A%0A
-import java.io.BufferedReader;%0Aimport java.io.IOException;%0Aimport java.io.InputStream;%0Aimport java.io.InputStreamReader;%0Aimport java.util.ArrayList;%0Aimport java.util.HashMap;%0Aimport java.util.List;%0Aimport java.util.Locale;%0Aimport java.util.Map;%0Aimport java.util.ResourceBundle;%0A%0A
 impo
@@ -1059,16 +1059,93 @@
 Tools;%0A%0A
+import java.io.IOException;%0Aimport java.io.InputStream;%0Aimport java.util.*;%0A%0A
 /**%0A * A
@@ -3031,25 +3031,24 @@
 getToken();%0A
-%0A
       final 
@@ -3239,9 +3239,12 @@
     
-%09
+    
 fina
@@ -3432,16 +3432,20 @@
         
+    
 + origTo
@@ -3851,17 +3851,16 @@
 );%0A  %7D%0A%0A
-%0A
   privat
@@ -3909,20 +3909,22 @@
 tStream 
-file
+stream
 ) throws
@@ -4013,340 +4013,197 @@
     
-InputStreamReader isr = null;%0A    BufferedReader br = null;%0A    try %7B%0A      isr = new InputStreamReader(file, getEncoding());%0A      br = new BufferedReader(isr);%0A      String line;%0A%0A      while ((line = br.readLine()) != null) %7B%0A        line = line.trim();%0A        if (line.length() %3C 1) %7B%0A          continue;%0A        %7D%0A        if (
+final Scanner scanner = new Scanner(stream, getEncoding());%0A    try %7B%0A      while (scanner.hasNextLine()) %7B%0A        final String line = scanner.nextLine();%0A        if (line.length() %3C 1 %7C%7C 
 line
@@ -4230,22 +4230,20 @@
  // 
-ignore
+ # =
  comment
 s%0A  
@@ -4238,17 +4238,16 @@
  comment
-s
 %0A       
@@ -4565,17 +4565,16 @@
       %7D%0A
-%0A
     %7D fi
@@ -4591,89 +4591,14 @@
     
-if (br != null) %7B%0A        br.close();%0A      %7D%0A      if (isr != null) %7B%0A        is
+scanne
 r.cl
@@ -4604,24 +4604,16 @@
 lose();%0A
-      %7D%0A
     %7D%0A  

simplify code by using Scanner