import React from 'react';
import Modularity from 'modularity-front';
import {Divider, Col , Row } from 'react-materialize';
import {OutTable, ExcelRenderer} from 'react-excel-renderer';
import CrudService from '../Services/CrudService';

import Dictionary from '../Services/DictionaryService';

let Module = Modularity.Module;

class ImportModule extends Modularity.Module {
	constructor(props) {
		super(props);
		this.state = {
			rows: [],
			cols: []
		}

		// add token
       	let propertiesService = {
            Table: this.Table.value,
            Token: this.Token.value,
            Service: (service) => this.updateService(service)
        }
        this.back_service = new CrudService(propertiesService);
	}
	
	updateService(s) { 
		this.service = s; 
	}

	sendData() {
		let data = {
			rows: this.state.rows || [],
			cols: this.state.cols || []
		};
		this.service.import(data).then((v) => {
			console.log(v);
		}).catch((e) => console.log(e))
	}

	fileHandler(event) {
	    let fileObj = event.target.files[0];
	    if(!fileObj)return;
	    //just pass the fileObj as parameter
	    ExcelRenderer(fileObj, (err, resp) => {
	      if(err){
	        console.log(err);
	      } else {
	      	let [cols, ...data] = resp.rows;
	      	cols = cols.map((name, key) => {return { name, key}});
	      	console.log(cols);
	      	console.log(data);
	        this.setState({
	          cols: cols,
	          rows: data,
	          results: true
	        });
	      }
	    });
	}

	render() {
		return <div>
			<input type="file" onChange={this.fileHandler.bind(this)} style={{"padding":"10px"}} />
			{this.state.results === true ?
				<div>
					<button onClick={() => this.sendData()}>{Dictionary.get("Import")}</button>
					<OutTable data={this.state.rows} columns={this.state.cols} tableClassName="ExcelTable2007" tableHeaderRowClass="heading" />
				</div>
			: null}
			{super.render()}
		</div>;
	}
}



ImportModule.EditPosition = "center";
ImportModule.Inputs = {
	Table: {
		type: Modularity.Module.Types.Text,
		defaultValue: "products"
	},
	Token: {
		type: Module.Types.Text,
		defaultValue: "123123"
	}
}

ImportModule.Outputs ={
}

ImportModule.Category = "Nikatlas";
export default ImportModule;