package com.kodcu.service.extension;

import com.kodcu.controller.ApplicationController;
import com.kodcu.other.Current;
import com.kodcu.other.IOHelper;
import com.kodcu.service.ThreadService;
import net.sourceforge.plantuml.FileFormat;
import net.sourceforge.plantuml.FileFormatOption;
import net.sourceforge.plantuml.SourceStringReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Objects;

import static java.nio.file.StandardOpenOption.*;

/**
 * Created by usta on 25.12.2014.
 */
@Component
public class PlantUmlService {

    private Logger logger = LoggerFactory.getLogger(PlantUmlService.class);

    @Autowired
    private Current current;

    @Autowired
    private ApplicationController controller;

    @Autowired
    private ThreadService threadService;

    public void plantUml(String uml, String type, String fileName) {
        Objects.requireNonNull(fileName);

        if (!fileName.endsWith(".png") && !"ascii".equalsIgnoreCase(type))
            return;

        String defaultScale = "\nskinparam dpi 300\n";

        if (!uml.contains("@startuml") && !uml.contains("@enduml")) {
            uml = defaultScale + uml;
            uml = "@startuml\n" + uml + "\n@enduml";
        } else {
            uml = uml.replaceFirst("@startuml", "@startuml" + defaultScale);
        }

        SourceStringReader reader = new SourceStringReader(uml);

        try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {

            if ("ascii".equalsIgnoreCase(type)) {
                String desc = reader.generateImage(os, new FileFormatOption(FileFormat.ATXT));

                return;
            }
            // default: png
            else {

                if (!current.currentPath().isPresent())
                    controller.saveDoc();

                Path path = current.currentPath().get().getParent();
                Path umlPath = path.resolve("images/").resolve(fileName);

                Integer cacheHit = current.getCache().get(fileName);

                int hashCode = (fileName + type + uml).hashCode();
                if (Objects.isNull(cacheHit) || hashCode != cacheHit) {

                    threadService.runTaskLater(() -> {
                        try {
                            String desc = reader.generateImage(os, new FileFormatOption(FileFormat.PNG));

                            Files.createDirectories(path.resolve("images"));

                            IOHelper.writeToFile(umlPath, os.toByteArray(), CREATE, WRITE, TRUNCATE_EXISTING);

                            controller.getLastRenderedChangeListener()
                                    .changed(null, controller.getLastRendered().getValue(), controller.getLastRendered().getValue());
                        } catch (Exception e) {
                            logger.error(e.getMessage(), e);
                        }
                    });
                }

                current.getCache().put(fileName, hashCode);
            }

        } catch (IOException e) {
            logger.info(e.getMessage(), e);
        }
    }
}

@@ -1187,37 +1187,32 @@
 && !
-%22ascii%22.equalsIgnoreCase(type
+fileName.endsWith(%22.svg%22
 ))%0A 
@@ -1565,283 +1565,198 @@
     
-SourceStringReader reader = new SourceStringReader(uml);%0A%0A        try (ByteArrayOutputStream os = new ByteArrayOutputStream()) %7B%0A%0A            if (%22ascii%22.equalsIgnoreCase(type)) %7B%0A                String desc = reader.generateImage(os, new FileFormatOption(FileFormat.ATXT));%0A
+Integer cacheHit = current.getCache().get(fileName);%0A%0A        int hashCode = (fileName + type + uml).hashCode();%0A%0A        if (Objects.nonNull(cacheHit))%0A            if (hashCode == cacheHit)
 %0A   
@@ -1776,24 +1776,25 @@
 return;%0A
+%0A
         
     %7D%0A  
@@ -1789,58 +1789,134 @@
     
-    %7D%0A            // default: png%0A            else
+SourceStringReader reader = new SourceStringReader(uml);%0A%0A        try (ByteArrayOutputStream os = new ByteArrayOutputStream())
  %7B%0A%0A
@@ -1923,28 +1923,24 @@
             
-    
 if (!current
@@ -1975,36 +1975,32 @@
                 
-    
 controller.saveD
@@ -2014,28 +2014,24 @@
             
-    
 Path path = 
@@ -2079,28 +2079,24 @@
             
-    
 Path umlPath
@@ -2158,106 +2158,38 @@
     
-    Integer cacheHit = current.getCache().get(fileName);%0A%0A                int hashCod
+FileFormat fileTyp
 e = 
-(
 fileName
  + t
@@ -2188,116 +2188,62 @@
 Name
- + type + uml).hashCode();%0A                if (Objects.isNull(cacheHit) %7C%7C hashCode != cacheHit) %7B%0A%0A        
+.endsWith(%22.svg%22) ? FileFormat.SVG : FileFormat.PNG;%0A%0A
     
@@ -2305,28 +2305,14 @@
     
-        try %7B%0A      
+try %7B%0A
     
@@ -2323,26 +2323,24 @@
             
-  
 String desc 
@@ -2391,32 +2391,21 @@
 ion(
-FileFormat.PNG));%0A%0A     
+fileType));%0A%0A
     
@@ -2416,27 +2416,24 @@
             
-   
 Files.create
@@ -2466,32 +2466,24 @@
 images%22));%0A%0A
-        
             
@@ -2590,32 +2590,24 @@
             
-        
 controller.g
@@ -2665,24 +2665,16 @@
         
-        
 .changed
@@ -2779,24 +2779,16 @@
         
-        
 %7D catch 
@@ -2799,32 +2799,24 @@
 eption e) %7B%0A
-        
             
@@ -2876,26 +2876,10 @@
     
-        %7D%0A        
+%7D%0A
     
@@ -2894,31 +2894,10 @@
 %7D);%0A
-                %7D%0A%0A    
+%0A%0A
     
@@ -2947,30 +2947,16 @@
 shCode);
-%0A            %7D
 %0A%0A      

Update plant uml extension to generate svg