/*
 * This file is part of the Poliqarp suite.
 * 
 * Copyright (C) 2004-2009 by Instytut Podstaw Informatyki Polskiej
 * Akademii Nauk (IPI PAN; Institute of Computer Science, Polish
 * Academy of Sciences; cf. www.ipipan.waw.pl).  All rights reserved.
 * 
 * This file may be distributed and/or modified under the terms of the
 * GNU General Public License version 2 as published by the Free Software
 * Foundation and appearing in the file gpl.txt included in the packaging
 * of this file.  (See http://www.gnu.org/licenses/translations.html for
 * unofficial translations.)
 * 
 * A commercial license is available from IPI PAN (contact
 * Michal.Ciesiolka@ipipan.waw.pl or ipi@ipipan.waw.pl for more
 * information).  Licensees holding a valid commercial license from IPI
 * PAN may use this file in accordance with that license.
 * 
 * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING
 * THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE.
 */

package ipipan.poliqarp.gui;

import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.LinkedList;
import java.util.regex.*;
import java.io.*;
import javax.swing.UIManager;
import ipipan.poliqarp.util.Pair;

public class ErrorTranslator implements MultilingualEntity {
   private Map<String, List<Pair<String, String> > > data;
   private List<Pair<String, String> > current;
   
   public ErrorTranslator() 
   {
      data = new HashMap<String, List<Pair<String, String> > >();
   }

   public void updateLanguage(Configuration cfg)
   {
      String lang = "en", opt = cfg.getConfigItem("language");
      if (opt.toLowerCase().equals("polish"))
         lang = "pl";
      current = data.get(lang);
      if (current == null) {
         try {
            current = readData(lang);
            data.put(lang, current);
         } catch (Exception e) { /* leave current set to null */ }
      }
   }

   public String translate(String error)
   {
      if (current == null)
         return error;
      for (Pair<String, String> pair : current) {
         error = error.replace(pair.first(), pair.second());
      }
      return error + ".";
   }

   private List<Pair<String, String> > readData(String language) throws IOException
   {
      BufferedReader f = new BufferedReader(new InputStreamReader(
         this.getClass().getResourceAsStream("errors/errors_" + language + ".txt"),
         "UTF-8"));
      List<Pair<String, String> > l = new LinkedList<Pair<String, String> >();
      String s;
      Pattern p = Pattern.compile("\"([^\"]+)\"\\s*:\\s*\"([^\"]+)\"");
      for (;;) {
         s = f.readLine();
         if (s == null)
            break;
         Matcher m = p.matcher(s);
         if (m.matches())
            l.add(new Pair(m.group(1), m.group(2)));
      }
      return l;
   }
}
