package com.eje_c.meganekko.xml.attribute_parser;

import android.content.Context;
import android.util.AttributeSet;

import com.eje_c.meganekko.AndroidResource;
import com.eje_c.meganekko.RenderData;
import com.eje_c.meganekko.SceneObject;
import com.eje_c.meganekko.VrContext;
import com.eje_c.meganekko.xml.XmlAttributeParser;

import java.io.IOException;

public class MeshParser implements XmlAttributeParser {

    @Override
    public void parse(Context context, SceneObject object, AttributeSet attributeSet) {

        // Already have mesh
        RenderData renderData = object.getRenderData();
        if (renderData != null && renderData.getMesh() != null) return;

        String mesh = attributeSet.getAttributeValue(NAMESPACE, "mesh");

        if (mesh != null) {
            
            if (renderData == null) {
                renderData = new RenderData();
                object.attachRenderData(renderData);
            }

            try {
                renderData.setMesh(VrContext.get().loadMesh(new AndroidResource(VrContext.get().getContext(), mesh)));
                return;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        String width = attributeSet.getAttributeValue(NAMESPACE, "width");
        String height = attributeSet.getAttributeValue(NAMESPACE, "height");
        if (width != null && height != null) {
            float w = Float.parseFloat(width);
            float h = Float.parseFloat(height);

            if (renderData == null) {
                renderData = new RenderData();
                object.attachRenderData(renderData);
            }

            renderData.setMesh(VrContext.get().createQuad(w, h));
        }
    }
}

@@ -517,166 +517,8 @@
  %7B%0A%0A
-        // Already have mesh%0A        RenderData renderData = object.getRenderData();%0A        if (renderData != null && renderData.getMesh() != null) return;%0A%0A
     
@@ -615,28 +615,16 @@
 null) %7B%0A
-            
 %0A       
@@ -632,147 +632,37 @@
     
-if (renderData == null) %7B%0A                renderData = new RenderData();%0A                object.attachRenderData(renderData);%0A            %7D
+ensureHaveRenderData(object);
 %0A%0A  
@@ -685,33 +685,43 @@
                 
-r
+object.getR
 enderData.setMes
@@ -705,32 +705,34 @@
 ct.getRenderData
+()
 .setMesh(VrConte
@@ -1243,78 +1243,114 @@
     
-if (renderData == null) %7B%0A                renderData = new RenderData(
+ensureHaveRenderData(object);%0A%0A            object.getRenderData().setMesh(VrContext.get().createQuad(w, h)
 );%0A 
@@ -1360,130 +1360,174 @@
     
+%7D%0A
     
-    object.attachRenderData(renderData);%0A            %7D%0A%0A            renderData.setMesh(VrContext.get().createQuad(w, h
+%7D%0A%0A    private void ensureHaveRenderData(SceneObject object) %7B%0A        if (object.getRenderData() == null) %7B%0A            object.attachRenderData(new RenderData(
 ));%0A

Refactor MeshParser