use oxygengine::user_interface::raui::{
   	core::prelude::*,
    material::prelude::*,
};
use serde::{Deserialize, Serialize};

use crate::{
	resources::stocks::Stocks,
	ui::components::stock::{stock, StockProps},
};

#[derive(MessageData, Debug, Clone, PartialEq, Eq)]
pub enum TopBarSignal {
	Register,
	SendStocks(Stocks),
}

#[derive(PropsData, Debug, Default, Clone, Serialize, Deserialize)]
struct TopBarState {
	pub stocks: Stocks,
}

fn use_tab_bar(context: &mut WidgetContext) {
	context.life_cycle.mount(|context| {
		context.signals.write(TopBarSignal::Register);
	});
	context.life_cycle.change(|context| {
		for msg in context.messenger.messages {
			if let Some(TopBarSignal::SendStocks(stocks)) = msg.as_any().downcast_ref() {
				let mut state = context.state.read_cloned_or_default::<TopBarState>();	
				state.stocks = stocks.to_owned();
				drop(context.state.write(state));
			}
		}
	});
}

#[pre_hooks(use_tab_bar)]
pub fn top_bar(mut context: WidgetContext) -> WidgetNode {
	let WidgetContext {
		key,
        state,
        ..
    } = context;

	let bkg = PaperProps { 
		frame: None, 
		..Default::default() 
	};
	let refe_state = state.read_cloned_or_default::<TopBarState>();
	let items_list = refe_state.stocks.stocks.iter()
        .map(|item| {
            widget! {
				(#{item.name} stock: { StockProps { cnt: item.stock, img: item.pic.to_owned() }})
            }
        })
        .collect::<Vec<_>>();
	
	let size = SizeBoxProps {
		height: SizeBoxSizeValue::Exact(32.), 
		width: SizeBoxSizeValue::Fill,
		..Default::default()
	};

	let size_ctn = Props::new(ContentBoxItemLayout {
		align: Vec2 { x: 0.5, y: 0. },
		margin: Rect {
			top: 4.,
			..Default::default()
		},
		..Default::default()
	})
	.with( SizeBoxProps {
		height: SizeBoxSizeValue::Fill, 
		width: SizeBoxSizeValue::Exact(400.),
		..Default::default()
	});
	
	widget!{
		(#{key} size_box: {size} {
			content = (#{"bkg"} paper: {bkg} [
				(#{"size_ctn"} size_box: {size_ctn} {
					content = (#{"h_box"} horizontal_box |[ items_list ]|)
				})
			])
		})
	}
}