import * as React from "react";
import {
    HostedWidgetCollection,
    HostedWidget
} from "./widget-com-server/widget-collection-controller";
import { WidgetSize } from "@talentsoft-opensource/integration-widget-component";

export interface WidgetAreaProps {
    widgets: HostedWidgetCollection;
}

function getFullWidgetUrl(widget: HostedWidget): string {
    const urlParams = new URLSearchParams();
    const params = widget.params;
    Object.keys(params).forEach(k => urlParams.append(k, params[k]));
    const query = urlParams.toString();
    return widget.url + "?" + query;
}

function getSizeClass(size: WidgetSize): string {
    switch (size) {
        case WidgetSize.Normal:
            return "";
        case WidgetSize.Enlarged:
            return "widget-area--widget-enlarged";
        case WidgetSize.Minimized:
            return "widget-area--widget-minimized";
        default:
            return "";
    }
}

export function WidgetArea(props: WidgetAreaProps) {
    const { widgets } = props;

    return (
        <div className="widget-area">
            {Object.values(widgets).map(w => {
                return (
                    <iframe
                        key={w.id}
                        id={w.id}
                        className={
                            "widget-area--widget " + getSizeClass(w.size)
                        }
                        src={getFullWidgetUrl(w)}
                    />
                );
            })}
        </div>
    );
}
