
/*
 * TemplateConfig.java
 *
 Copyright (C) 2008 fwd
 
   This file is part of I2PSnarkXL.
 
   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, 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 org.i2p.i2psnarkxl.template.util.conf;

import java.io.*;
import java.nio.charset.*;
import java.util.ArrayList;
import java.util.SortedMap;
import java.util.Set;
import java.util.Iterator;
import net.i2p.I2PAppContext;
import net.i2p.util.Log;
//
public class TemplateConfig {
    private static TemplateConfig _instance = new TemplateConfig();
    public static TemplateConfig instance() { return _instance; }
    
    public static final String[] supportedCharset = {"ISO-8859-1","ISO-8859-2","ISO-8859-3","ISO-8859-4","ISO-8859-5","ISO-8859-6","ISO-8859-7","ISO-8859-8","ISO-8859-9","ISO-8859-10","ISO-8859-11","ISO-8859-12","ISO-8859-13","ISO-8859-14","ISO-8859-15","ISO-2022-JP","ISO-2022-KR","GB18030","Big5","Big5-HKSCS","EUC-JP","EUC-KR","GBK","JISX201-1976","KOI8-R","CP437","UTF-8","SJIS"};
    public static final ArrayList finalCharset = getSystemAndSupportedCharsets();
    
    private static String defaultConfigFile = "default.config";
    private I2PAppContext _context;
    private static Log _log;
    private static ArrayList defaultConfigKeys = null;
    private static ArrayList userConfigKeys = null;
    /** Creates a new instance of TemplateConfig */
    public TemplateConfig() {
        _context = I2PAppContext.getGlobalContext();
        _log = _context.logManager().getLog(TemplateConfig.class);
    }
    
    // worst case! if a loop call this we get a high CPU and disc usage! call this method only for testing cases!
    public static String getPropertyFromFile(String key, String path, String filename) {
        String proberty = null;
        File file = new File(path + "/" + filename);
        
        if(file.exists()){
            FileReader fin = null;
            try {
                fin = new FileReader(file);
                BufferedReader in = new BufferedReader(fin);
                String temp;
                while ((temp = in.readLine()) != null) {
                    if(temp.startsWith(key + "=")){
                        proberty = temp.substring(key.length() + 1); // this could be "" ( length == 0) but not null!                        
                        break;
                    }
                }
                fin.close();
            } catch (java.io.IOException ioe) {
                _log.warn( "file "+ file.getPath() + "not found", ioe);
                return null;
            }
        } 
        
        return proberty;
    }
    
    public static ArrayList getKeysFromFile(String key, String path, String filename){
        File file = new File(path + "/" +  filename);
        ArrayList tempArray = null;
        if(file.exists()){
            FileReader fin = null;
            try {
                fin = new FileReader(file);
                BufferedReader in = new BufferedReader(fin);
                String temp;
                while ((temp = in.readLine()) != null) {
                    if(tempArray == null){
                        tempArray = new ArrayList();
                    }
                    if(tempArray != null && temp.startsWith(key )){
                        tempArray.add(temp);
                    }
                }
                fin.close();               
            } catch (java.io.IOException ioe) {
                _log.warn( "file "+ file.getPath() + "not found", ioe);
                return null;
            }
        }
        return tempArray;
    }
    
    public static String getDefaultProberty(String proberty, String path){
        if(defaultConfigKeys == null){
            defaultConfigKeys = new ArrayList(getKeysFromFile("key_",path, defaultConfigFile));
        }
        if(defaultConfigKeys != null){
            for(int i = 0; i < defaultConfigKeys.size(); i++){
                if(((String)defaultConfigKeys.get(i)).startsWith(proberty + "=")){
                    return ((String)defaultConfigKeys.get(i)).substring(proberty.length() + 1);
                }
            }
        }
        return null;
    }
    
     public static String getUserProberty(String proberty){
        if(userConfigKeys == null){
            return ("ERROR in userconfig");
        }
        if(userConfigKeys != null){
            for(int i = 0; i < userConfigKeys.size(); i++){
                if(((String)userConfigKeys.get(i)).startsWith(proberty + "=")){
                    return ((String)userConfigKeys.get(i)).substring(proberty.length() + 1);
                }
            }
        }
        return null;
    }
     
    public static void resetDefaultConfig(){
        defaultConfigKeys = null;
    }
    
     public static void resetUserConfig(){
        userConfigKeys = null;
    }
    
     public static ArrayList getUserKeys(String userConfigFile ,String path){
         if(userConfigKeys == null){
            userConfigKeys = new ArrayList(getKeysFromFile("user_key_",path, userConfigFile)); 
        }
         if(userConfigKeys != null){
             ArrayList userKeys = null;
             for(int i = 0; i < userConfigKeys.size(); i++){
                 if(((String)userConfigKeys.get(i)).indexOf("=") != -1){
                     if(userKeys == null){
                         userKeys = new ArrayList();
                     }
                     if(userKeys != null){
                         String newUserkeyTmp = ((String)userConfigKeys.get(i)).substring(0,((String)userConfigKeys.get(i)).indexOf("=")) ;
                         if(!userKeys.contains(newUserkeyTmp)){
                             userKeys.add(new String(newUserkeyTmp));
                         }
                     }
                     
                 }
             }
             if(userKeys != null){// is null than if the file exists and all should be fine than proberly it's not a ANSI file ... ?unicode?
                 //toDo ?-make a byte reading methode for unicode files-?
                 return new ArrayList(userKeys);
             }
         }
         return null;
     }
     
     public static ArrayList getSystemAndSupportedCharsets(){
        String[] systemCharsets = getSystemCharsets();
        String[] toIncludeCharset = new String[supportedCharset.length];
        ArrayList charsetArray = new ArrayList();
        int included=0;
        
        for(int j=0 ; j<supportedCharset.length ;j++) {
            boolean isInSystemCharset = false;
            for(int i=0 ; i<systemCharsets.length ;i++) {
                
                if(systemCharsets[i].equalsIgnoreCase(supportedCharset[j])){
                    isInSystemCharset=true;
                    break;
                }
            }
            if(!isInSystemCharset){
                toIncludeCharset[included]=supportedCharset[j];
                included++;
            }
        }
        
        int allCharsetSize=included+systemCharsets.length;
        //String[] allCharsets = new String[allCharsetSize];
        
        for(int i=0 ; i<systemCharsets.length ;i++) {
            //allCharsets[i ]= systemCharsets[i];
            if(!charsetArray.contains(systemCharsets[i])){
                charsetArray.add(systemCharsets[i]);
            }
        }
        int j=systemCharsets.length;
        for(int i=0 ; i<included ;i++) {
            //allCharsets[j]= toIncludeCharset[i];
            if(!charsetArray.contains(systemCharsets[i])){
                charsetArray.add(toIncludeCharset[i]);
            }
            j++;
        }
        
        return charsetArray;
    }
    
    public static String[] getSystemCharsets(){
        SortedMap them = Charset.availableCharsets() ;
        Set es = them.entrySet();
        String[] systemCharsets = new String[es.size()];
        int i=0;
        for(Iterator it =es.iterator() ; it.hasNext() ;) {
            Object next = it.next();
            String charset = (String)next.toString();
            systemCharsets[i]=charset.substring(charset.indexOf("=")+1);
            i++;
        }
        return systemCharsets;
    }
}
