import React from 'react';
import LinkManager from 'modularity-front';
import Modularity from 'modularity-front';
import {Button ,Col,Row, Input} from 'react-materialize';
import Pagination from '../../Modules/Pagination';
import Card from '../../Modules/Card';
import Repository from '../../Services/Repository';
import Dictionary from '../../Services/DictionaryService';
import FilterModule from '../../Modules/FilterModule';

import DoneIcon from '@material-ui/icons/Done';
import SearchBar from '../../Modules/searchbar';
import ChipModule from '../../Modules/Chip';
import Toast from '../../helpers/Toast';

import Dropdown from '../../Modules/UserInputs/DropdownFilter'

import './presentation1.css';
let Module = Modularity.Module;


class PresantationModule extends Modularity.Module {
	constructor(props) {
		super(props);
		this.state = {
			FilterInputs:[],
			page:1,
			totalPages:1,
			products:{},
			search:{},
			filterVisible: false
		}

		this.orderingFilter = this.getOrderingFilter();
		
		this.perPage = 9;
		this.Repository.onUpdate((repo) => this.updateRepository(repo))
		this.filters = [];
		this.search = { type:"search", values: [], field: "name,description"};
		this.setSearch(this.search);

		this.Filters.onUpdate((v) => this.updateFilters(v));
		let session = sessionStorage.getItem("FilterInputs");
		if(!session) {
			this.getModel();
		} else {
			this.state.FilterInputs = JSON.parse(session);
			this.filters = this.state.FilterInputs;
			this.update();
		}
	}

	getModel() {
		let ProductsRepo = new Repository("products");
		ProductsRepo.model().then((model) => {
			let inputs = [];
			for(var i in model) {
				if(model[i].Filter) {
					//TODO update these 2 lines logic
					if(model[i].Filter.type === 'search' && model[i].Filter.field === 'name'){
						this.setSearch(model[i].Filter);
					}
					else{
						inputs.push(model[i].Filter);
					}	
				}
			}
			return inputs;
		})
		.then((v) => v.reduce((initial,b) => b.order > -1 ? initial.push(b) && initial : initial, []))
		.then((v) => v.sort((a,b) => a.order - b.order))
		.then((v) =>  {
			this.setState({FilterInputs:v})
			sessionStorage.setItem("FilterInputs", JSON.stringify(v));
			this.update();
		});
	}


	updateFilters(filters){
		if(filters  === undefined){
			return;
		}
		this.filters = filters;
		this.update();
		this.setState({FilterInputs: filters});
		sessionStorage.setItem("FilterInputs", JSON.stringify(filters));
	}

	getOrderingFilter() {
		return (sessionStorage.getItem("Ordering") && JSON.parse(sessionStorage.getItem("Ordering"))) ||
		{
			type: 'ascending',
			options: { 'price': 'Τιμή', 'name':'Όνομα προϊόντος' },
			field: 'price',
			required: true,
			value: 'price'
		};
	}

	update(){	
		sessionStorage.setItem("Ordering", JSON.stringify(this.orderingFilter));
		this.updateRepository(new Repository('products',null,[...this.filters, this.orderingFilter,this.search]));
	}
	updateRepository(repo) { 
		this.back_service = repo;
		this.getData();
	}
	updatePattern(v){
		window.history.replaceState({}, '','/search/'+ v); // Implement Into CoreSystem
	}
	getData(page = 1){
		this.back_service.count()
		.then((result) => {
			let totalPages = Math.ceil(result[0].counter / this.perPage );
			this.setState({totalPages});
		})
		this.back_service.getPage(page,this.perPage)
		.then((result) => this.parseData(result))
		.then((data) => {
			this.setState({products:data})
			this.forceUpdate()
		})	
		.catch((e) => {
			console.log(e)
		})
	}

	parseData(result){
		return result.map((item) => {
			let val = {
				id: item.id,
				name:item.name,
				description:item.description || "",
				shortdescription:item.shortdescription || "",
				price:item.price,
				image:item.image || "/logo.png",
				quantity: 1
			}
			return val;
		});
	}

	setSearch(filter) {
		let route = (this.RoutingSystem.getRoute().params || {}).value;
		filter.values = [route || ''];
		filter.field = "name,description";
		sessionStorage.setItem("SearchFilter" , JSON.stringify(filter));
		this.search = filter;
		//this.update();
	}

	setSearchFilter(v) {
		let filter = {
			type:"search",
			values:[v],
			field:"name,description"
		}
		sessionStorage.setItem("SearchFilter" , JSON.stringify(filter));
		this.search = filter;
		this.updatePattern(v)
		this.update();
	}

	pageChanged(v) {
		this.getData(v);
    }
	
	addProduct (v){
		this.selectedProduct.set(v);
		Toast.success(v.name + " added to your cart")
		this.forceUpdate();
	}

	render() {
		let page = this.state.page;
		let totalPages = this.state.totalPages;
		return(
			<div className="present_container">
				<Row>
					<Col className={"filter_container " + (this.state.filterVisible && 'show')} l={3}>
						<FilterModule className="filter_layout" 
						Inputs={this.state.FilterInputs}
						Filters={(filters) => this.updateFilters(filters)}/>
						<div className="badge" onClick={() => {
							this.setState({filterVisible: !this.state.filterVisible})
						}}>
							<i className="fa fa-filter"></i>
						</div>
					</Col>
					<Col l={9}>
						<div className="chips_container">
							<SearchBar SearchBar={{defaultValue:(this.RoutingSystem.getRoute().params ||{}).value}} SearchData={(v) => this.setSearchFilter(v)}/>
							<div className="filters">
								<div className="orderBy">
									<div className="tool" onClick={() => {
											this.orderingFilter = {
												...this.orderingFilter,
												type: this.orderingFilter.type === "ascending" ? 'descending' : 'ascending'
											}
											this.update();
										}}>
										<i className={"fa fa-sort-"+(this.orderingFilter.type === "ascending" ? 'up' : 'down')}></i>
									</div>
									<Dropdown filter={this.orderingFilter} defaultValue={this.orderingFilter.field} Filters={(data) => {
										let field = data.values[0];
										this.orderingFilter = {
											...this.orderingFilter,
											field,
											value: field
										};
										this.update();
									}}/>
								</div>
								<div className="chip_module">
									<ChipModule  Inputs={this.state.FilterInputs} Filters={(filters) => this.updateFilters(filters)} />
								</div>
							</div>
						</div>
						<div className="products_container">
							<PresentData products={this.state.products} addProduct={(e) => this.addProduct(e)} onClick={(p) => {
								this.CoreSystem.go('/product/' + p.id);
							}}/>
							<Pagination selected={page} lastPage={totalPages} onPage={(v) => this.pageChanged(v)} />
						</div>
					</Col>
				{super.render()}
				</Row>
			</div>
			);
				    
	}
}


class PresentData extends React.Component{
	constructor(props){
		super(props);
	}
	
	render(){
		if(!this.props.products.length) {
			return <h6>{Dictionary.get("No products")}</h6>;
		}
		let prods = this.props.products;
		const prodList = Object.keys(prods).map((item,index) => {
			let key = item;//item.id;
			let p = prods[key];//item;
			return <Card id={key} key={p.name} className="col s12 m6 l4" 
			CardTitle={p.name} Price={p.price} 
			CardBody={<span dangerouslySetInnerHTML={{__html: p.shortdescription}}></span>} CardImage={p.image} 
			product = {(prod) => this.props.addProduct(p)} 
			onClick={() => this.props.onClick(p)}/>;
		})
		return(
			<Row>
				{prodList}
			</Row>
			)
	}
}


PresantationModule.EditPosition = "center";
PresantationModule.Inputs = {
	Repository: {
		type: Module.Types.Object,
	},
	Page:{
		type:Module.Types.Number,
	},

	Url:{
		type:Module.Types.Text,
		defaultValue:""
		},
	
	Filters:{
		type:Module.Types.Object
	}
}



PresantationModule.Outputs = {
	selectedProduct:{

	}
}

PresantationModule.Category = "Sxoinas Packages";
export default PresantationModule;