/**
 * 
 */
package org.javarosa.core.services.locale;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.javarosa.core.util.Map;
import org.javarosa.core.util.OrderedHashtable;

/**
 * @author ctsims
 *
 */
public class LocalizationUtils {
    /**
     * @param resourceName A path to a resource file provided in the current environment
     *
     * @return a dictionary of key/value locale pairs from a file in the resource directory 
     * @throws IOException 
     */
    public static Map<String,String> parseLocaleInput(InputStream is) throws IOException {
            // TODO: This might very well fail. Best way to handle?
            Map<String,String> locale = new Map<String, String>();
            int chunk = 100;
            InputStreamReader isr;
            isr = new InputStreamReader(is,"UTF-8");
            boolean done = false;
            char[] cbuf = new char[chunk];
            int offset = 0;
            int curline = 0;

                String line = "";
                while (!done) {
                    int read = isr.read(cbuf, offset, chunk - offset);
                    if(read == -1) {
                        done = true;
                        if(line != "") {
                            parseAndAdd(locale, line, curline);
                        }
                        break;
                    }
                    String stringchunk = String.valueOf(cbuf,offset,read);
                    
                    int index = 0;
                    
                    while(index != -1) {
                        int nindex = stringchunk.indexOf('\n',index);
                        //UTF-8 often doesn't encode with newline, but with CR, so if we 
                        //didn't find one, we'll try that
                        if(nindex == -1) { nindex = stringchunk.indexOf('\r',index); }
                        if(nindex == -1) {
                            line += stringchunk.substring(index);
                            break;
                        }
                        else {
                            line += stringchunk.substring(index,nindex);
                            //Newline. process our string and start the next one.
                            curline++;
                            parseAndAdd(locale, line, curline);
                            line = "";
                        }
                        index = nindex + 1;
                    }
                }
            return locale;
        }

        private static void parseAndAdd(OrderedHashtable locale, String line, int curline) {

            //trim whitespace.
            line = line.trim();
            
            //clear comments - require space before them to differentiate from markdown '#'
            while(line.indexOf(" #") != -1) {
                line = line.substring(0, line.indexOf(" #"));
            }
            if(line.indexOf('=') == -1) {
                // TODO: Invalid line. Empty lines are fine, especially with comments,
                // but it might be hard to get all of those.
                if(line.trim().equals("")) {
                    //Empty Line
                } else {
                    System.out.println("Invalid line (#" + curline + ") read: " + line);
                }
            } else {
                //Check to see if there's anything after the '=' first. Otherwise there
                //might be some big problems.
                if(line.indexOf('=') != line.length()-1) {
                    String value = line.substring(line.indexOf('=') + 1,line.length());
                    locale.put(line.substring(0, line.indexOf('=')), parseValue(value));
                }
                 else {
                    System.out.println("Invalid line (#" + curline + ") read: '" + line + "'. No value follows the '='.");
                }
            }
        }
        
        /*
         * Helper to replace our markdown encodings with what we want
         */
        
        private static String parseValue(String value){
            String ret = value.replace("\\#", "#");
            ret = ret.replace("\\n", "\n");
            return ret;
        }
}

@@ -60,173 +60,173 @@
 ort 
-java.io.IOException;%0Aimport java.io.InputStream;%0Aimport java.io.InputStreamReader;%0A%0Aimport org.javarosa.core.util.Map;%0Aimport org.javarosa.core.util.OrderedHashtable
+org.javarosa.core.util.Map;%0Aimport org.javarosa.core.util.OrderedHashtable;%0A%0Aimport java.io.IOException;%0Aimport java.io.InputStream;%0Aimport java.io.InputStreamReader
 ;%0A%0A/
@@ -312,20 +312,10 @@
 ram 
-resourceName
+is
  A p
@@ -2682,16 +2682,40 @@
 .trim();
+%0A%0A            int i = 0;
 %0A       
@@ -2753,58 +2753,51 @@
 nts 
-- require space before them to differentiate from 
+except if they have backslash before them (
 mark
@@ -2804,16 +2804,18 @@
 down '#'
+s)
 %0A       
@@ -2825,16 +2825,21 @@
   while(
+(i = 
 line.ind
@@ -2848,18 +2848,49 @@
 Of(%22
- 
 #%22)
+)
  != -1
+ && !(line.charAt(i-1) == '%5C%5C')
 ) %7B%0A
@@ -2934,26 +2934,9 @@
 (0, 
-line.indexOf(%22 #%22)
+i
 );%0A 

fix pound sign encoding