package utils;

import com.intellij.ide.fileTemplates.FileTemplate;
import com.intellij.ide.fileTemplates.FileTemplateManager;
import com.intellij.openapi.project.Project;
import org.apache.velocity.runtime.parser.ParseException;
import org.jetbrains.annotations.Nullable;
import wrappers.PackageTemplateWrapper;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Properties;

/**
 * Created by CeH9 on 15.07.2016.
 */
public class AttributesHelper {

    public static final ArrayList<String> listAttributesToRemove = new ArrayList<String>() {{
        add(FileTemplate.ATTRIBUTE_NAME);
        add(FileTemplate.ATTRIBUTE_PACKAGE_NAME);
        add(PackageTemplateWrapper.ATTRIBUTE_BASE_NAME);
    }};

    public static String[] getUnsetAttrs(FileTemplate fileTemplate, Project project) {
        try {
            return getWithoutDefaultAttributes(fileTemplate.getUnsetAttributes(new Properties(), project));
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }

    private static String[] getWithoutDefaultAttributes(String[] unsetAttributes) {
        ArrayList<String> list = new ArrayList<>();
        list.addAll(Arrays.asList(unsetAttributes));
        Iterator<String> iterator = list.iterator();
        while (iterator.hasNext()) {
            if (listAttributesToRemove.contains(iterator.next())) {
                iterator.remove();
            }
        }
        return list.toArray(new String[list.size()]);
    }

    @Nullable
    public static FileTemplate getTemplate(String name) {
        FileTemplate fileTemplate = FileTemplateManager.getDefaultInstance().getTemplate(name);
        if (fileTemplate != null) {
            return fileTemplate;
        } else {
            return FileTemplateManager.getDefaultInstance().getInternalTemplate(name);
        }
    }

}

@@ -165,16 +165,52 @@
 roject;%0A
+import com.intellij.util.ArrayUtil;%0A
 import o
@@ -1660,29 +1660,27 @@
 Template
- fileTemplate
+Manager ftm
  = FileT
@@ -1710,24 +1710,60 @@
 ltInstance()
+;%0A%0A        FileTemplate result = ftm
 .getTemplate
@@ -1784,65 +1784,59 @@
   if
- (fileTemplate !
+( result =
 = null
+ 
 ) 
-%7B%0A            return file
+result = ftm.getInternal
 Template
 ;%0A  
@@ -1831,16 +1831,22 @@
 Template
+(name)
 ;%0A      
@@ -1851,88 +1851,49 @@
     
-%7D else %7B%0A            return FileTemplateManager.getDefaultInstance().getInternal
+if( result == null ) result = ftm.getJ2ee
 Temp
@@ -1904,24 +1904,25 @@
 (name);%0A
+%0A
         
 %7D%0A    %7D%0A
@@ -1905,27 +1905,40 @@
 name);%0A%0A        
-%7D
+return result;
 %0A    %7D%0A%0A%7D%0A

fix template getter