import React from "react";
import DealsListDeal from "./DealsListDeal";
import SingleDeal from "./SingleDeal";

export default class DealsList extends React.Component
{
	constructor(props)
	{
		super(props);
		this.list_ref = React.createRef();
		this.items_ref = [];
	}

	_scrollToDeal = (index) => 
	{
		const element = this.list_ref.current.children[index];
		const y = (element.getBoundingClientRect().top + window.scrollY - 90);
		window.scrollTo({top: y, behavior: 'smooth'});
	}

	_handle_onSelectDeal = (deal_id, index) => 
	{
		const { onSelectDeal } = this.props;
		onSelectDeal(deal_id);
		setTimeout(() => 
		{
			this._scrollToDeal(index);
		}, 50);
	}

	_handle_onCloseDeal = () => 
	{
		const { onCloseDeal } = this.props;
		onCloseDeal();

		setTimeout(() => 
		{
			const element = this.list_ref.current;
			const y = (element.getBoundingClientRect().top + window.scrollY - 160);
			window.scrollTo({top: y, behavior: 'smooth'});
		}, 50);
	}

	render()
	{
		const { status, deals, questionnaire_status, dealSelected, onCloseDeal, onDealsUpdate, onDealContractsUpdate, onQuestionnaire } = this.props;

		return (
			<div className="contractStatus_list" ref={ this.list_ref }>
				{ deals.list !== undefined && deals.list !== null && deals.list.map((deal, index) => 
				{
					if(dealSelected === deal.opp_number)
					{
						return (<SingleDeal 
							router={ this.props.router } 
							key={ index } 
							index={ index } 
							ref={ ref => this.items_ref[index] = ref } 
							status={ status } 
							dealSelected={ dealSelected } 
							deals={ deals } 
							questionnaire_status={ questionnaire_status } 
							onFocusDeal={ () => this._scrollToDeal(index) } 
							onCloseDeal={ this._handle_onCloseDeal } 
							onDealsUpdate={ onDealsUpdate } 
							onDealContractsUpdate={ onDealContractsUpdate } 
							onQuestionnaire={ onQuestionnaire } 
							{ ...deal } 
						/>)
					}
					else
					{
						return (
							<DealsListDeal 
								key={ index } 
								index={ index } 
								ref={ ref => this.items_ref[index] = ref } 
								{ ...deal } 
								onSelectDeal={ this._handle_onSelectDeal } 
							/>
						)
					}
				} )}
			</div>
		)
	}
}