-- P5-5762: create view for product interior images urls

DROP VIEW IF EXISTS v_interior_image_urls;

CREATE VIEW v_interior_image_urls AS
SELECT
    "product-printproducts".productid,
    interiors.print_id,
    "product-printproducts".groupid as product_group,
    rooms.id as room_id,
    rooms.name as room_name,
    interiors.position,
    room_types.name as room_type,
    case
        when interiors.room_id is null then
            '/interior-images/' ||  interiors.id || '.jpg'
        else
            '/products/' || "product-printproducts".productid || '.jpg?interior[image]=' || rooms.name
            || '&interior[type]=' || "product-groups".group
            || ( CASE WHEN "product-printproducts".typeid = 3 AND print_file_dpi.value::numeric > 0 THEN '&interior[height]=' || round(print_file_height.value::numeric * 2.54 / print_file_dpi.value::numeric) ELSE '' END)
            || ( CASE WHEN "product-printproducts".typeid <> 3 AND focus_x_point2.value::numeric > 0 THEN '&primary_area[x]=' || round(focus_x_point2.value::numeric, 3) ELSE '' END)
            || ( CASE WHEN "product-printproducts".typeid <> 3 AND focus_y_point2.value::numeric > 0 THEN '&primary_area[y]=' || round(focus_y_point2.value::numeric, 3) ELSE '' END)
    end as uri
from interiors
join "product-printproducts" on "product-printproducts".printid = interiors.print_id
join "product-groups" on "product-groups".groupid = "product-printproducts".groupid
left join rooms on interiors.room_id = rooms.id
left join room_types on room_types.id = rooms.room_type_id
left join "product-products_fields" focus_x_point on focus_x_point.productid = "product-printproducts".productid and focus_x_point.fieldid = 31
left join "product-products_fields" focus_y_point on focus_y_point.productid = "product-printproducts".productid and focus_y_point.fieldid = 32
left join "product-products_fields" focus_x_point2 on focus_x_point2.productid = "product-printproducts".productid and focus_x_point2.fieldid = 33
left join "product-products_fields" focus_y_point2 on focus_y_point2.productid = "product-printproducts".productid and focus_y_point2.fieldid = 34
left join "product-products_fields" print_file_height on print_file_height.productid = "product-printproducts".productid and print_file_height.fieldid = 42
left join "product-products_fields" print_file_dpi on print_file_dpi.productid = "product-printproducts".productid and print_file_dpi.fieldid = 43;
