import os
import random
import bpy
import product_gen.generate_lamp
import rendering.setup_scene
import rendering.setup_renderer

def generate(shape_parameters, output_prefix, is_final=False):
    
    rendering.setup_renderer.setup_renderer(shape_parameters)
    
    rendering.setup_scene.initialize_scene(shape_parameters)
    
    # Generate models
    models = product_gen.generate_lamp.generate_models(shape_parameters)
    
    # Optimize geometries for render
    product_gen.generate_lamp.optimize_for_render(models)

    # Set up materials and textures
    color = (0.1, 0.1, 0.1)
    
    colors = [(0.1, 0.1, 0.1),
              (0.68, 0.68, 0.68),
              (0.033, 0.065, 0.376),
              (0.019, 0.202, 0.032)]
    color = random.choice(colors)
    if "bio" not in shape_parameters["shape"]:
        colormap = {"shade": color,
                    "base": (132.0/255.0, 64.0/255.0, 11.0/255.0),
                    "chord": (5.0/255.0, 5.0/255.0, 5.0/255.0)}
    else:
        colormap = {"shade": color}
        
    product_gen.generate_lamp.apply_textures(colormap, models)
    
    rendering.setup_scene.setup_scene(shape_parameters)
    
    # Do rendering
    prefix = os.getcwd() + "/" + output_prefix + "/" + output_prefix
    if is_final:
        bpy.context.scene.render.filepath = prefix + "_kitchen.png"
        bpy.ops.render.render(write_still=True)
        
        bpy.context.scene.render.filepath = prefix + "_hall.png"
        bpy.ops.render.render(write_still=True)
        
        bpy.context.scene.render.filepath = prefix + "_landing.png"
        bpy.ops.render.render(write_still=True)
        
    else:
        bpy.context.scene.render.filepath = prefix + ".png"
        bpy.ops.render.render(write_still=True)
        
    bpy.ops.wm.save_as_mainfile(filepath=prefix + ".blend") 
    
    return shape_parameters