import React from 'react';

import LinkManager from 'modularity-front';
import Modularity from 'modularity-front';
import {Icon,Input, Button ,Col,Row } from 'react-materialize';

import Moment from 'react-moment';
import './Table.css';

let Module = Modularity.Module;

class TableModule extends Modularity.Module {
	constructor(props) {
        super(props);
		this.state = {
        }
        this.EditedTable.set(this.TableData.value);
        this.TableData.onUpdate((e) => this.forceUpdate());
	}
    
    change = (data,row_id) => {
        console.log("event fid with",row_id)
        this.EditedRow.set(data);
        let updated_data = this.TableData.value;
        updated_data[row_id] = data;
        this.EditedTable.set(updated_data);
        this.forceUpdate();
    }


    row_edited = (data,row_id) => {
        this.onEdit.set(data);
    }
    
    row_deleted = (data,row_id) => {
       this.onDelete.set(data)
    }
    resolve(value, header) {
        if (header && typeof(header) === "object") {
            switch(header.type) {
                case 'date': 
                    return <Moment format="HH:mm DD/MM/YYYY">{value}</Moment>
                    
                default:
                    return value;
            }
        }
        return value;
    }
    render(){
        var headers;
        var data;
        headers = Object.keys(this.TableHeaders.value || (this.TableData.value && (this.TableData.value.length > 0) && this.TableData.value[0]) || {}).map((key,index)=>{
            return(<th key={index}>{key}</th>)
        })

        data = (this.TableData.value || []).map((item,ind)=>{
           
            return(
                <tr key={'' + item.id + item.price + item.quantity}>
                    {Object.keys(this.TableHeaders.value || {}).map((header,index)=>{
                        let input = this.TableHeaders.value[header];
                        if(header === 'image'){
                            return (<td key={header}>
                                <img src={item[input.field || input]} />
                            </td>)
                        } else if (input === '-index-' && item.id) {
                            return <td key={item.id+'index'}>{ind+1}</td>
                        } else {
                            let field = input.field || input;
                            let value = this.resolve(item[field], input);
                            if (value && typeof(value) === "object") {
                                value = value.name || value[0] || value;
                            } else if (value) {
                                if (input.precision && !isNaN(value)) {
                                        value = value.toFixed(input.precision);
                                }
                                if (input.suffix) {
                                    value = value + input.suffix;
                                }
                                if (input.prefix) {
                                    value = input.prefix + value;
                                }
                            }
                            return(<td key={header}>
                                <Editable   row_id={ind} value={value} header_key={input.field || input} 
                                            onChange={this.change} row={item} edit={this.LiveEdit.value}/>
                            </td>)
                        }
                    }
                    )}
                    {this.props.onEdit ? (<EditButton row_id ={ind} row = {item}   row_edited = {this.row_edited}/>):
                    (null)}
                    {this.props.onDelete ? (<DeleteButton row_id={ind} row = {item} row_deleted  = {this.row_deleted}/>):
                    (null)}
                    {this.props.onView ? (<ViewButton row_id={ind} row = {item} view_row  = {(e) => this.props.onView(e)}/>):
                    (null)}

                </tr>
            )
        
        })

        return(
            <div>
                {super.render()}
                {data.length ?

                <table className={this.TableClass.value + ""}>
                    <thead>
                        <tr>{headers}</tr>
                    </thead>
                    <tbody>
                        { data }
                    </tbody>
                </table>
                : <div className="NothingHere"> Nothing Here! </div>}
            </div>
        );
	
    }
}


TableModule.Inputs = {
    LiveEdit:{
        type:Module.Types.Boolean,
        defaultValue:false
    },
    TableHeaders:{
        type: Module.Types.Object,
        defaultValue:{
            "Name" : "key1",
            "Age" : "key2",
            "Value": "key3"
        }
    },
	TableData: {
		type: Module.Types.Array,
		defaultValue: [
            {
             "key1" : "Natalie",
             "key2" : "20",
             "key3": "120"
            },
            {
             "key1" : "Somer",
             "key2" : "10 y",
             "key3": "1000"
            },
            {
             "key1" : "Panos",
             "key2" : "3y",
             "key3": "500"
            }
            ],
        arrType: Module.Types.Object
		
    },
    TableClass:{
        type:Module.Types.Text,
        defaultValue:"striped centered"
    }
}



class Editable extends React.Component{
    constructor(props){
        super(props)
        this.state = {
            value: this.props.value,
            LiveEdit :false
        }    
    }

    edit(e) {
        e.preventDefault();
        this.setState({LiveEdit:true})
    }

    handleSubmit = (e) =>{
        e.preventDefault();
        let key = this.props.header_key;
        let output = this.props.row;
        output[key] = e.target.value;
        this.props.onChange(output,this.props.row_id)   
    }
    _handleKeyPress = (e) => { 
        if (e.key === 'Enter') {
            this.handleSubmit(e)
            this.setState({LiveEdit:false})
        }
    }
    blur = (e) => {
        this.handleSubmit(e)
        this.setState({LiveEdit:false})
    }
    render(){
        let { onBlur, onChange, value, ...props } = this.props;
        return (this.state.LiveEdit ? 
                <input style={{width: "auto"}} value={this.state.value} onChange={(e) => this.setState({value: e.target.value})} onBlur = {this.blur} onKeyPress={this._handleKeyPress} />   
            :
                <div onClick={(e) => this.props.edit && this.edit(e)}>{this.state.value}</div>
            );
    }
}



class EditButton extends React.Component{
    constructor(props){
        super(props)
    }   

    _editRow = (e) => {
        e.preventDefault();
        this.props.row_edited(this.props.row,this.props.row_id)
    }

    render(){
        return(
            <td style={{width:"60px"}}
                    ><Button onClick={this._editRow} className="btn-floating">
                        <Icon tiny>edit</Icon>
                    </Button>
            </td>
        )
    }
}


class DeleteButton extends React.Component{
    constructor(props){
        super(props)
    }

    _DeleteRow = (e) => {
        e.preventDefault();
        this.props.row_deleted(this.props.row,this.props.row_id)
        
    }
    
    render(){
        return(
            <td style={{width:"60px"}}>
                    <Button onClick={this._DeleteRow} className="btn-floating">
                        <Icon tiny>delete</Icon>
                    </Button>
            </td>
        )
    }
}


class ViewButton extends React.Component{
    constructor(props){
        super(props)

    }
    

    render(){
        return(
            <td style={{width:"60px"}}>
                    <Button onClick={(e) => this.props.view_row(this.props.row)} className="btn-floating">
                        <Icon tiny>remove_red_eye</Icon>
                    </Button>
            </td>
            )
    }
}


TableModule.Outputs = {
    EditedTable:{
        type:Module.Types.Array,
        arrType:Module.Types.Object
    },

    EditedRow : {
        type:Module.Types.Object
    },

    onEdit: {
        type:Module.Types.Object
    },
    onDelete: {
        type:Module.Types.Object
    }
}
TableModule.Category = "sxoinas";
TableModule.EditPosition = "center";



export default TableModule;