/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package svgconverter;

import java.io.*;
import java.util.*;
import java.io.File;
import org.w3c.dom.Document;
import org.w3c.dom.*;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;


/**
 *
 * @author Pap
 */
public class Main {

    public static class MapEntry {
        Vector<Integer> sequence = new Vector<Integer>();
        int cnt = 1;
        public String ToString() {
            String result = "";
            for(int i = 0; i < this.sequence.size(); i++)
                result += this.sequence.get(i).intValue() + " ";
            return result;
        }
    }

    static public double[] parseHTMLColor(String s) {
        s = s.toLowerCase();
//        System.out.println(s);
        if(s.length() == 4)
            s = "#" + s.charAt(1) + s.charAt(1) + s.charAt(2) + s.charAt(2) + s.charAt(3) + s.charAt(3);
        double gcol[] = new double[3];
      for(int c = 0; c < 3; c++) {
          char high = s.charAt(1 + c * 2);
          char low = s.charAt(1 + c * 2 + 1);
          double v = 0;
          if((high >= '0') && (high <= '9'))
              v = (byte)(high - '0');
          else
              v = 10 + (byte)(high - 'a');
          double col = v * 16;
          if((low >= '0') && (low <= '9'))
              v = (byte)(low - '0');
          else
              v = 10 + (byte)(low - 'a');
          col += v;
          gcol[c] = col;
      }
      return gcol;
    }

    static public int readCoords(String[] t, int pos, double[] val) {
        String[] coo = t[pos].split(",");
        if(coo.length == 2) {
//            System.out.println("read 2 coords from " + t[pos]);
            pos++;
            val[0] = Double.parseDouble(coo[0]);
            val[1] = Double.parseDouble(coo[1]);
        } else {
//            System.out.println("read 2 * 1 coords");
            val[0] = Double.parseDouble(t[pos++]);
            val[1] = Double.parseDouble(t[pos++]);
        }
        return pos;
    }

    static String[] splitCommands(String ss) {
        String[] t = ss.split(" ");
        LinkedList<String> list = new LinkedList<String>();
        for(int ti = 0; ti < t.length; ti++) {
            String s = t[ti];
            int pos = 0;
            String cur = "";
            while(pos < s.length()) {
                char c = s.charAt(pos);
                String cs = "" + c;
                if(cs.matches("[a-zA-Z]")){
                    list.add(cur);
                    list.add(cs);
                    cur = "";
                } else if(c == ',') {
                    list.add(cur);
                    cur = "";
                } else if(c == '-') {
                    list.add(cur);
                    cur = cs;
                } else {
                    cur += c;
                }
                pos++;
            }
            list.add(cur);
        }

        int cnt = 0;
        for(int i = 0; i < list.size(); i++)
            if(!list.get(i).equals("")) {
                cnt++;
//                System.out.println("Parsed [" + list.get(i) + "]");
            }
        String[] result = new String[cnt];
        cnt = 0;
        for(int i = 0; i < list.size(); i++)
            if(!list.get(i).equals(""))
                result[cnt++] = list.get(i);
        return result;
    }

    public static void main(String[] args) {
        try {

            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            Document doc = docBuilder.parse (new File(Config.fileName));

            // normalize text representation
            doc.getDocumentElement ().normalize ();
            String viewBoxString = doc.getDocumentElement().getAttribute("viewBox");
            System.out.println("Main: " + viewBoxString + "\n");
            String[] tok = viewBoxString.split(" ");
            SVGDrawer.docMinX = Integer.parseInt(tok[0]);
            SVGDrawer.docMinY = Integer.parseInt(tok[1]);
            SVGDrawer.docMaxX = Integer.parseInt(tok[2]);
            SVGDrawer.docMaxY = Integer.parseInt(tok[3]);

            double AVOID_ONE_EPSILON = 0.00000001;
            SVGDrawer.docInvSizeX = 1.0 / (double)(SVGDrawer.docMaxX - SVGDrawer.docMinX + AVOID_ONE_EPSILON);
            SVGDrawer.docInvSizeY = 1.0 / (double)(SVGDrawer.docMaxY - SVGDrawer.docMinY + AVOID_ONE_EPSILON);

            NodeList gList = doc.getElementsByTagName("path");
            int totalG = gList.getLength();
            System.out.println("Number of G elements : " + totalG);

            LinkedList<Path> paths = new LinkedList<Path>();
            int numCoords = 0;

            double val[] = new double[2];

            int cmdCntMove = 0;
            for(int s=0; s<gList.getLength() ; s++){
                Path path = new Path();

                Element pElement = (Element)gList.item(s);
                String col = pElement.getAttribute("fill");
                if(!"".equals(col)) {
//                      System.out.println("Fill: "+ col);
                    path.color = parseHTMLColor(col);
                };
                String style = pElement.getAttribute("style");
                if(!"".equals(style)) {
                    col = style.split("fill:")[1];
//                        System.out.println("Style: "+ col);
                    path.color = parseHTMLColor(col);
                };
/*
                double scaleX = 1.0;
                double scaleY = 1.0;
                String transformdata = pElement.getAttribute("transform");
                if(transformdata.length() > 0) {
                    System.out.println("transform: " + transformdata);
                    System.out.println("transform: " + transformdata.substring(transformdata.indexOf("(") + 1, transformdata.indexOf(")")));
                    String[] t = transformdata.substring(transformdata.indexOf("(") + 1, transformdata.indexOf(")")).split(",");
                    scaleX = Double.parseDouble(t[0]);
                    scaleY = Double.parseDouble(t[1]);
                    if(scaleX != scaleY) {
                        System.out.println("ERROR");
                        System.exit(0);
                    }
                }
*/
                String pdata = pElement.getAttribute("d");
                int pos = 0;
                double mX = 0;
                double mY = 0;
//                String[] t = pdata.split(" ");
                String[] t = splitCommands(pdata);
                for(int i = 0; i < t.length; i++) {
                    if(!t[i].matches("[a-zA-Z]"))
                        t[i] = "" + (Double.parseDouble(t[i]));
//                        t[i] = "" + (Double.parseDouble(t[i]) * scaleX * Config.GSCALE);
                }
                path.commands = t;
                if(path.commands.length > 0)
                    paths.add(path);
            }
            SVGDrawer drawer = new SVGDrawer(paths);
            try{ System.in.read(); } catch (Exception e) {};
        }catch (SAXParseException err) {
        System.out.println ("** Parsing error" + ", line "
             + err.getLineNumber () + ", uri " + err.getSystemId ());
        System.out.println(" " + err.getMessage ());

        }catch (SAXException e) {
        Exception x = e.getException ();
        ((x == null) ? e : x).printStackTrace ();

        }catch (Throwable t) {
        t.printStackTrace ();
        }
        System.exit (0);

/*

     try{
        double width = 0;
        double height = 0;
        double[] viewBox = new double[4];
        int doubled = 0;
        LinkedList<Path> paths = new LinkedList<Path>();

        HashMap<String, Boolean> segMap = new HashMap<String, Boolean>();
        // Open the file that is the first
        // command line parameter
        FileInputStream fstream = new FileInputStream("data/test3.svg");
        // Get the object of DataInputStream
        DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String strLine;
        //Read File Line By Line
        while ((strLine = br.readLine()) != null)   {
          // Print the content on the console
          if(strLine.contains("<svg")) {
              String[] t = strLine.split(" ");
              for(int i = 0; i < t.length; i++) {
                  if(t[i].contains("width"))
                      width = Double.parseDouble(t[i].split("=")[1].split("\"")[1].split("pt")[0]);
                  if(t[i].contains("height"))
                      height = Double.parseDouble(t[i].split("=")[1].split("\"")[1].split("pt")[0]);
              }
              //"width="1308pt" height="970pt" viewBox="0 0 1308 970" version="1.1" xmlns="http://www.w3.org/2000/svg">
          }
          if(strLine.contains("path")) {
              System.out.println (strLine);
              Path p = new Path();
              paths.add(p);
              String t[] = strLine.split("\"");
//              System.out.println (t[1]);
              for(int c = 0; c < 3; c++) {
                  char high = t[1].charAt(1 + c * 2);
                  char low = t[1].charAt(1 + c * 2 + 1);
                  double v = 0;
                  if((high >= '0') && (high <= '9'))
                      v = (byte)(high - '0');
                  else
                      v = 10 + (byte)(high - 'a');
                  double col = v * 16;
                  if((low >= '0') && (low <= '9'))
                      v = (byte)(low - '0');
                  else
                      v = 10 + (byte)(low - 'a');
                  col += v;
                  p.color[c] = col;
              }
              String s = t[5];
              t = s.split(" ");
              int pos = 4;
              while(pos < t.length) {
                  if(t[pos].equals("C")) {
                      pos++;
                      Segment seg = new Segment();
                      seg.type = Segment.TYPE.PATH;
                      for(int i = 0; i < 6; i++)
                          seg.coords.add(Double.parseDouble(t[pos + i]));
                      p.segments.add(seg);
                      pos += 6;
                      String id = "";
                      String rid = "";
                      for(int i = 0; i < seg.coords.size(); i++) {
                         rid = " " + seg.coords.get(i) + rid;
                      }
                     Boolean d = segMap.get(id);
                     if(d == null) {
                         segMap.put(id, true);
                         segMap.put(rid, true);
                     } else {
//                             System.out.println("Already exists");
                         doubled++;
                     }
                  } else if(t[pos].equals("L")) {
                      pos++;
                      Segment seg = new Segment();
                      seg.type = Segment.TYPE.LINE;
                      for(int i = 0; i < 2; i++)
                          seg.coords.add(Double.parseDouble(t[pos + i]));
                      p.segments.add(seg);
                      pos += 2;
                  } else if(t[pos].equals("M")) {
                      pos++;
                      // ignore moves
                      pos += 2;
                  } else if(t[pos].equals("Z")) {
                      pos++;
                      // end of command
//                      break;
                  } else {
                      System.out.println("Unknown command: " + t[pos]);
                  }
              }

          }
        }
        //Close the input stream
        in.close();

        System.out.println("Dim: " + width + " x " + height);
        int segCnt = 0;
        int coordCnt = 0;
        Iterator<Path> iter = paths.iterator();
        while(iter.hasNext()) {
            Path p = iter.next();
            segCnt += p.segments.size();
            Iterator<Segment> i2 = p.segments.iterator();
            while(i2.hasNext()) {
                Segment s = i2.next();
                coordCnt += s.coords.size();
            }
        }
        System.out.print(paths.size() + " pathes   " + segCnt + " segments   " + coordCnt + " coordinates  " + doubled + " doubled");

        }catch (Exception e){//Catch exception if any
          System.err.println("Error: " + e.getMessage());
        }
*/
    }

}
