/**
 *  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 3 of the License, 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, see <http://www.gnu.org/licenses/>.
 */

package net.froihofer.xnote;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.swing.JFileChooser;

/**
 *
 * @author Lorenz Froihofer
 * @version $Id$
 */
public class Converter {

  /**
   * @param args the command line arguments
   */
  public static void main(String[] args) {
    try {
      JFileChooser jfc = new JFileChooser();
      //jfc.setFileFilter(new DirectoryFilter());
      jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
      if (jfc.showOpenDialog(null) != JFileChooser.APPROVE_OPTION) {
        return;
      }
      SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy - HH:mm");
      byte[] tmp = sdf.format(new Date()).getBytes();
      byte[] date = new byte[32];
      Arrays.fill(date, (byte)0);
      System.arraycopy(tmp, 0, date, 0, tmp.length);


      File dir = jfc.getSelectedFile();
      String newFileName = null;
      ScriptEngineManager factory = new ScriptEngineManager();
      ScriptEngine engine = factory.getEngineByName("JavaScript");
      engine.put("newFileName", newFileName);
      for (File f : dir.listFiles(new XNoteFilter())) {
        File savedFile = new File(f.getAbsolutePath()+".sav");
        newFileName = f.getParent() + File.separator + engine.eval("escape('"+f.getName()+"').replace(/\\//g,'%2F')");
        File nf = new File(newFileName);
        f.renameTo(savedFile);
        FileInputStream fis = new FileInputStream(savedFile);
        FileOutputStream fos = new FileOutputStream(nf);
        byte[] oldheader = new byte[16];
        fis.read(oldheader);
        fos.write(oldheader);
        byte[] content = new byte[(int)(savedFile.length()-16l)];
        int bytesRead = fis.read(content);
        if (bytesRead < 32) {
          // Pre 2.1.0 file format for sure, write date.
          fos.write(date);
        }
        else {
          boolean found = false;
          for (int i = 0; i<32 && !found; i++) {
            //If we find a 0 byte in the first 32 characters,
            //then we assume it's a date as produced by XNote version 2.1.0.
            if (content[i] == 0) found = true;
          }
          if (!found) fos.write(date);
        }
        fos.write(content, 0, bytesRead);
        fis.close();
        fos.flush();
        fos.close();
      }
    }
    catch (Exception e) {
      System.err.println("Failed to update XNote messages.");
      e.printStackTrace();
    }
  }

  private static class XNoteFilter implements java.io.FileFilter {

    public boolean accept(File pathname) {
      return pathname.getName().endsWith(".xnote");
    }

  }
}

