import * as React from "react";
import { RouteComponentProps } from "react-router-dom";
import { OrderListTable } from "./Orders/OrderListTable";
import { OrderController_GetOrders } from "../../../../apiClient/routes";
import { Pager } from "../../../common/pager";
import { IOrderListQueryFilter, IOrderVM, IPagedQueryResult, ISortItem } from "../../../../apiModels/ViewModels";
import { GetObject } from "../../../../services/localStorageService";
import http from "../../../../services/httpService";

type OrderListProps = RouteComponentProps;
type OrderListState = {
	filter: IOrderListQueryFilter,
	orders: Array<IOrderVM>,
	pageIndex: number,
	sortItem: ISortItem,
	totalPages: number
}

const PAGE_SIZE = 20;

class OrderList extends React.Component<OrderListProps, OrderListState> {
	state = {
		filter: {
			orderStateID: undefined,
			userID: 0
		} as IOrderListQueryFilter,
		orders: new Array<IOrderVM>(),
		pageIndex: 0,
		sortItem: {
			direction: 'descending',
			expression: 'OrderedDate'
		} as ISortItem,
		totalPages: 1
	};

	async componentDidMount() {
		const user = GetObject();

		if (user !== null) {
			let orders = {} as IPagedQueryResult<IOrderVM>;
			let pagedQuery = {
				filter: {
					orderStateID: undefined,
					userID: user.unique_name
				} as IOrderListQueryFilter,
				pageIndex: 0,
				pageSize: PAGE_SIZE,
				sorting: [{
					direction: 'descending',
					expression: 'OrderedDate'
				} as ISortItem]
			};

			await http.post<IPagedQueryResult<IOrderVM>>(OrderController_GetOrders, pagedQuery).then(async (response) => {
				orders = await response.data;
				await this.calculateTotalPages(response.data.totalCount);
			})
			.catch(e => {
				console.log(e);
				this.setState({ ...this.state });
			});

			this.setState({ orders: orders.data });
		} else {
			this.props.history.push("/login");
		}
	}

	componentDidUpdate(prevProps: OrderListProps, prevState: OrderListState) {
		if (this.state.filter.orderStateID !== prevState.filter.orderStateID ||
			this.state.pageIndex !== prevState.pageIndex ||
			this.state.sortItem !== prevState.sortItem) {
			const { filter, pageIndex, sortItem } = this.state;

			let pagedQuery = {
				filter: filter,
				pageIndex: pageIndex,
				pageSize: PAGE_SIZE,
				sorting: [sortItem]
			};

			Promise.resolve(http.post<IPagedQueryResult<IOrderVM>>(OrderController_GetOrders, pagedQuery).then(async (response) => {
				const orders = await response.data;
				await this.calculateTotalPages(response.data.totalCount);
				this.setState({ orders: orders.data });
			})
			.catch(e => {
				console.log(e);
				this.setState({ ...this.state });
			}));
		}
	}

	async calculateTotalPages(ordersTotalCount: number): Promise<void> {
		let totalPages = Math.floor(ordersTotalCount / PAGE_SIZE);

		if ((ordersTotalCount % PAGE_SIZE) > 0) {
			totalPages++;
			this.setState({ totalPages });
		} else if (ordersTotalCount === 0) {
			this.setState({ totalPages: 0 });
		} else if (totalPages <= this.state.pageIndex) {
			this.setState({ pageIndex: 0, totalPages });
		} else {
			this.setState({ totalPages });
		}
	}

	handleOrderItemClick = (orderItemId: number): void => {
		this.props.history.push(`/account/order/${orderItemId}`);
	}

	handlePageChange = (newPageIndex: number): void => {
		this.setState({ pageIndex: newPageIndex });
	}

	handlePageShift = (shift: number): void => {
		const { pageIndex, totalPages } = this.state;

		if (shift === 1) {
			if ((pageIndex + 1) < totalPages) {
				this.setState({ pageIndex: pageIndex + 1 });
			}
		} else {
			if ((pageIndex - 1) >= 0) {
				this.setState({ pageIndex: pageIndex - 1 });
			}
		}
	}

	handleSortItemChange = (propName: string): void => {
		let sortItem = { ...this.state.sortItem };

		if (sortItem.expression === propName) {
			sortItem.direction = sortItem.direction === "ascending" ? "descending" : "ascending";
			this.setState({ sortItem });
		} else {
			sortItem.direction = "ascending";
			sortItem.expression = propName;
			this.setState({ sortItem });
		}
	}

	render() {
		const { orders, pageIndex, totalPages, sortItem } = this.state;
		return (
			<React.Fragment>
				<section className="order-list">
					<div className="container">

						{/* Dropdown pro filtrovani order state */}

						<div className="row ">
							<div className="col-lg-12">
								<OrderListTable
									onColumnNameClick={this.handleSortItemChange}
									onOrderItemClick={this.handleOrderItemClick}
									orders={orders}
									sortItem={sortItem}
								/>
							</div>
						</div>

						<Pager
							onPageChange={this.handlePageChange}
							onPageShift={this.handlePageShift}
							pageIndex={pageIndex}
							totalPages={totalPages}
						/>

					</div>
				</section>
			</React.Fragment>
		);
	}
}

export default OrderList;