package fr.adrienbrault.idea.symfony2plugin.util.service;

import com.intellij.openapi.project.Project;
import fr.adrienbrault.idea.symfony2plugin.Symfony2ProjectComponent;
import org.jetbrains.annotations.Nullable;

import java.io.File;
import java.util.*;

public class ServiceXmlParserFactory implements ServiceFileInterface {

    protected static Map<Project, Map<Class, ServiceXmlParserFactory>> instance = new HashMap<Project, Map<Class, ServiceXmlParserFactory>>();

    protected Project project;
    protected ServiceParserInterface serviceParser;

    protected Long lastUpdate;
    protected Object items;

    public ServiceXmlParserFactory(Project project, Class serviceParser) {
        this.project = project;

        try {
            this.serviceParser = (ServiceParserInterface) serviceParser.newInstance();
        } catch (InstantiationException ignored) {
        } catch (IllegalAccessException ignored) {
        }

    }

    @Nullable
    public Object parser() {

        Symfony2ProjectComponent symfony2ProjectComponent = this.project.getComponent(Symfony2ProjectComponent.class);

        File serviceFile = symfony2ProjectComponent.getPathToProjectContainer();
        if (serviceFile == null) {
            return null;
        }

        Long serviceModTime = serviceFile.lastModified();
        if (this.items != null && serviceModTime.equals(this.lastUpdate)) {
            return this.items;
        }

        // @TODO: check null
        return this.items = this.serviceParser.parser(serviceFile);
    }

    public void setCacheInvalid() {
       this.lastUpdate = null;
    }

    public static ServiceXmlParserFactory getInstance(Project project, Class object){

        Map<Class, ServiceXmlParserFactory> projectInstance = instance.get(project);

        if(projectInstance == null) {
            projectInstance = new HashMap<Class, ServiceXmlParserFactory>();
            instance.put(project, projectInstance);
        }

        ServiceXmlParserFactory projectPhpTypeInstance = projectInstance.get(object);
        if(projectPhpTypeInstance == null) {
            projectPhpTypeInstance = new ServiceXmlParserFactory(project, object);
            projectInstance.put(object, projectPhpTypeInstance);
        }

        return projectPhpTypeInstance;

    }

}

@@ -669,16 +669,50 @@
 t, Class
+%3C? extends ServiceParserInterface%3E
  service
@@ -804,33 +804,8 @@
 er =
- (ServiceParserInterface)
  ser
@@ -1696,23 +1696,64 @@
 t, Class
- object
+%3C? extends ServiceParserInterface%3E serviceParser
 )%7B%0A%0A    
@@ -2089,22 +2089,29 @@
 nce.get(
-object
+serviceParser
 );%0A     
@@ -2224,22 +2224,29 @@
 roject, 
-object
+serviceParser
 );%0A     
@@ -2276,14 +2276,21 @@
 put(
-object
+serviceParser
 , pr

make service factory calls more type secure