import React from 'react';
import Modularity from 'modularity-front';
import {Row,CardTitle,Button,Col,Card} from 'react-materialize';

import Modules from '../Modules/index.js';

import FilterModule from '../Modules/FilterModule.js';

import './TableData.css';

let {
	Table,
	Pagination
} = Modules;

let Module = Modularity.Module;

let pTimeout = (time, item) => {
    return new Promise((res,rej) => {
        setTimeout(() => res(item), time);
    });
}
class TableData extends Modularity.Module {
	constructor(props) {
		super(props);
		this.state = {
            page: 1,
            data: [],
            totalPages: 1
		}

        this.service.onUpdate(() => this.serviceUpdate(this.state.page));
        this.serviceUpdate(this.state.page);
	}
	   
    serviceUpdate(page = 1) {
        let Service = this.service.value;
        if(!Service.count)
            return;
        let perPage = this.perPage.value;
        return Service.count().then(([{counter}]) => {
            let totalPages = parseInt((counter / perPage) + 0.999);
            page = page <= totalPages ? page : totalPages; 
            this.setState({totalPages, page});
            return Service.getPage(page, perPage);
        })
        .then((data) => {
            this.setState({data});
        }).catch((e) => console.log(e));
    }
    pageChanged(v) {
        this.serviceUpdate(v);
    }

	render() {
        let page     = this.state.page,
            totalPages = this.state.totalPages,
            data  = this.state.data;     
        let TableView = 
                <Row style={{display: 'flex'}} key={'Table'+this.getId()}>
                    <Col s={12}>
                        <Table  TableHeaders={this.TableHeaders.value} TableData={data} 
                                TableClass={this.TableClass.value} onView = {this.props.onView}/>
                        <Pagination selected={page} lastPage={totalPages} onPage={(v) => this.pageChanged(v)} />
                    </Col>
                </Row>;
        
		return [TableView,super.render()];
				    
	}
}


TableData.Inputs = {
    service: {
        type: Module.Types.Object,
        defaultValue: {}
    },
	perPage: {
		type: Module.Types.Number,
        defaultValue: 10
	},
    TableHeaders:{
        type: Module.Types.Object,
        defaultValue:{
            "Id" : "id",
            "Name" : "name",
            "Value": "price"
           }
    },
    TableClass:{
        type: Module.Types.Text,
        defaultValue:"striped centered"
    }
}

TableData.Outputs = {
}

TableData.Category = "Higher Modules";
TableData.EditPosition = "top-right";
export default TableData;