namespace _zeitbild.frontend_web.widgets.sources
{
	
	/**
	 */
	type type_entry = {
		id : _zeitbild.frontend_web.type.calendar_id;
		name : string;
		access_level : _zeitbild.frontend_web.type.enum_access_level;
	};
	
	
	/**
	 */
	export class class_widget_sources extends _zeitbild.class_widget
	{
		
		/**
		 */
		private keys : Array<string>;
		
		
		/**
		 */
		private data : Record<string, type_entry>;
		
		
		/**
		 */
		private action_select : ((entry : type_entry) => void);
		
		
		/**
		 */
		public constructor(
			entries : Array<type_entry>,
			options : {
				action_select ?: ((entry : type_entry) => void);
			} = {}
		)
		{
			options = Object.assign(
				{
					"action_select": (calendar_id) => {},
				},
				options
			);
			super();
			this.keys = [];
			this.data = {};
			entries.forEach(
				(entry) => {
					const key : string = entry.id.toFixed(0);
					this.keys.push(key);
					this.data[key] = entry;
				}
			);
			this.action_select = options.action_select;
		}
		
		
		/**
		 * [implementation]
		 */
		public async load(
			target_element : Element
		) : Promise<void>
		{
			target_element.innerHTML = await _zeitbild.frontend_web.helpers.template_coin(
				"widget-sources",
				"main",
				{
					"entries": (
						(
							await _zeitbild.frontend_web.helpers.promise_row<string>(
								this.keys
								.map(
									(key) => () => {
										const entry : type_entry = this.data[key];
										return _zeitbild.frontend_web.helpers.template_coin(
											"widget-sources",
											"entry",
											{
												"name": entry.name,
												// "access_level": entry.access_level, // TODO
												// TODO centralize
												"color": lib_plankton.color.output_hex(
													lib_plankton.color.give_generic(
														(entry.id - 1),
														{
															"saturation": 0.375,
															"value": 0.375,
														}
													),
												),
												"rel": key,
											}
										);
									}
								)
							)
						)
						.join("")
					),
				}
			);
			target_element.querySelectorAll(".sources-entry").forEach(
				(element) => {
					element.addEventListener(
						"click",
						(event) => {
							const key : string = element.getAttribute("rel");
							const entry : type_entry = this.data[key];
							this.action_select(entry);
						}
					);
				}
			);
			return Promise.resolve<void>(undefined);
		}
			
	}
	
}
