import Image 
import ImageDraw
import numpy
from .scaler import scaler
from .layer import DEFAULT_DISPLAY_LAYER_SET
from ipkiss.primitives.elements import gds_layer_element
from ipkiss.all import *

__all__ = ["structure_to_image"]

def __add_layer_to_bitmap(struct, bitmap_draw, layer, display_style, scale):
    for e in struct.elements:
        if not isinstance(e, gds_layer_element):
            continue
        if e.layer != layer:
            continue
        if not isinstance(e, gds_shape_element):
            continue
        S = scale.map_shape_to_list(e.shape.transform_copy(e.transformation))
        if e.line_width != 0.0:
            bitmap_draw.line(S, display_style.color, width = int(numpy.ceil(scale.map_length(e.line_width))))
        else:
            bitmap_draw.polygon(S, fill = display_style.color)
    return

def structure_to_image(struct, bitmap_size, box = None, display_styles = DEFAULT_DISPLAY_LAYER_SET):
    SI = struct.size_info()
    S = struct.flat_copy()
    if box == None:
        box = (SI.left, SI.right, SI.bottom, SI.top)
    if bitmap_size[0] == None:
        bitmap_size = (int(bitmap_size[1] * (box[1] - box[0]) / (box[3]- box[2])), bitmap_size[1])
    elif bitmap_size[1] == None:
        bitmap_size = (bitmap_size[0],int(bitmap_size[0] * (box[3] - box[2]) / (box[1]- box[0])))
    scale = scaler(box, bitmap_size)
    bitmap = Image.new("RGB", bitmap_size, "white")
    draw = ImageDraw.Draw(bitmap)
    for layer, style in display_styles:
        __add_layer_to_bitmap(S, draw, layer, style, scale)
    del draw
    return bitmap
        
        