/*
 * The MIT License
 *
 * Copyright 2013 Venkat Ram Akkineni.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package org.netbeans.modules.plantumlnb.ui.io;

import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.nio.charset.Charset;
import net.sourceforge.plantuml.FileFormat;
import net.sourceforge.plantuml.FileFormatOption;
import net.sourceforge.plantuml.SourceStringReader;
import org.netbeans.modules.plantumlnb.PrettyPrinter;
import org.netbeans.modules.plantumlnb.ui.options.PlantUMLPanel;
import static org.netbeans.modules.plantumlnb.ui.options.PlantUMLPanel.DOT_MANUAL_MODE_DOT_PATH;
import org.openide.filesystems.FileObject;
import org.openide.util.NbPreferences;

/**
 *
 * @author venkat
 * @author markiewb (refactoring)
 */
public class PUMLGenerator {

    private static final Logger logger = Logger.getLogger(PUMLGenerator.class.getName());
    private static PUMLGenerator INSTANCE;

    public static PUMLGenerator getInstance() {
        if (null == INSTANCE) {

            INSTANCE = new PUMLGenerator();
        }
        return INSTANCE;
    }

    private PUMLGenerator() {
    }

    public String generateIntoString(FileObject inputFile, FileFormat fileFormat) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {

            final boolean manual = NbPreferences.forModule(PlantUMLPanel.class).getBoolean(PlantUMLPanel.DOT_MANUAL_MODE, false);
            if (manual) {
                String path = NbPreferences.forModule(PlantUMLPanel.class).get(DOT_MANUAL_MODE_DOT_PATH, "");
                System.setProperty("GRAPHVIZ_DOT", path);
            } else {
                System.clearProperty("GRAPHVIZ_DOT");
            }

            /**
             * TODO: This particular constructor seems to use UTF-8 no matter which charset is passed as an argument.
             * Replace this to use user specified charset in the future.
             */
            SourceStringReader reader = new SourceStringReader(inputFile.asText(), null);
            // Write the first image to "os"
            String desc = reader.generateImage(os, new FileFormatOption(fileFormat));
            return new String(os.toByteArray(), Charset.forName("UTF-8"));
        } catch (IOException ex) {
            logger.log(Level.WARNING, ex.getMessage());
        } finally {
            try {
                os.close();
            } catch (IOException ex) {
                logger.log(Level.WARNING, ex.getMessage());
            }
        }
        return null;
    }


public void generateIntoFile(FileObject inputFile, File outputFile, FileFormat fileFormat) {
        String content = generateIntoString(inputFile, fileFormat);
        FileWriter fw = null;
        BufferedWriter bw = null;
        try {

            outputFile.createNewFile();
            fw = new FileWriter(outputFile);
            bw = new BufferedWriter(fw);
            bw.write(PrettyPrinter.formatXml(content));
            bw.flush();

        } catch (IOException ex) {
            logger.log(Level.WARNING, ex.getMessage());
        } finally {
            try {
                if (fw != null) {
                    fw.close();
                }
                if (bw != null) {
                    bw.close();
                }
            } catch (IOException ex) {
                logger.log(Level.WARNING, ex.getMessage());
            }
        }
    }

}

@@ -1427,16 +1427,17 @@
 harset;%0A
+%0A
 import n
@@ -1689,24 +1689,25 @@
 ntUMLPanel;%0A
+%0A
 import stati
@@ -1791,16 +1791,88 @@
 T_PATH;%0A
+%0Aimport java.io.BufferedOutputStream;%0Aimport java.io.FileOutputStream;%0A%0A
 import o
@@ -2388,22 +2388,22 @@
  public 
-String
+byte%5B%5D
  generat
@@ -2407,22 +2407,21 @@
 rateInto
-String
+Bytes
 (FileObj
@@ -2449,33 +2449,32 @@
 rmat fileFormat)
- 
 %7B%0A        ByteAr
@@ -3419,19 +3419,8 @@
 urn 
-new String(
 os.t
@@ -3435,35 +3435,8 @@
 ay()
-, Charset.forName(%22UTF-8%22))
 ;%0A  
@@ -3745,20 +3745,25 @@
  %7D%0A%0A
-%0A
+    
 public 
-void
+String
  gen
@@ -3771,20 +3771,22 @@
 rateInto
-File
+String
 (FileObj
@@ -3803,25 +3803,8 @@
 ile,
- File outputFile,
  Fil
@@ -3837,25 +3837,26 @@
     
-String content = 
+return new String(
 gene
@@ -3863,22 +3863,21 @@
 rateInto
-String
+Bytes
 (inputFi
@@ -3895,171 +3895,205 @@
 mat)
-;%0A        FileWriter fw = null
+, Charset.forName(%22UTF-8%22))
 ;%0A    
+%7D%0A%0A
     
-BufferedWriter bw = null;%0A        try %7B%0A%0A            outputFile.createNewFile();%0A            fw = new FileWriter(outputFile
+public void generateIntoFile(FileObject inputFile, File outputFile, FileFormat fileFormat) %7B%0A        byte%5B%5D content = generateIntoBytes(inputFile, fileFormat
 );%0A 
@@ -4103,314 +4103,137 @@
     
-  
-  bw = new BufferedWriter(fw);%0A            bw.write(PrettyPrinter.formatXml(content));%0A            bw.flush();%0A%0A        %7D catch (IOException ex) %7B%0A            logger.log(Level.WARNING, ex.getMessage());%0A        %7D finally %7B%0A            try %7B%0A                if (fw != null) %7B%0A                    fw.close(
+try (BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(outputFile))) %7B%0A            output.write(content
 );%0A 
@@ -4247,102 +4247,24 @@
     
-  
-  %7D%0A                if (bw != null) %7B%0A                    bw.close();%0A                %7D%0A    
+output.flush();%0A
     
@@ -4286,36 +4286,32 @@
 Exception ex) %7B%0A
-    
             logg
@@ -4346,38 +4346,24 @@
 Message());%0A
-            %7D%0A
         %7D%0A  

Fix problem when exporting binary image