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

import ListModule from '../HigherModules/ListModule.js';

import CrudService from '../Services/CrudService.js';

import './CrudListPackage.css';
let Module = Modularity.Module;
class CrudListPackage extends Modularity.Module {
	constructor(props) {
		super(props);
		this.state = {
            service: null
		}

        this.headers = this.TableHeaders.value;

        let table = this.TableName.value;
        if (this.RouterDependable.value) { // Search route for table
            let route = this.RoutingSystem.getRoute();
            let regex = /\/[A-Za-z]+\/?/g;
            let found = route.url.match(regex);
            if(found.length){
                table = found[0].replace('/', '');   
            }
        }

        let propertiesService = {
            Table: table,
            Token: this.Token.value,
            Service: (service) => this.updateService(service)
        }

        this.back_service = new CrudService(propertiesService);
        this.TableName.onUpdate((v) => { this.back_service.Table.update(v);this.forceUpdate(); });
        this.Token.onUpdate((v) => { this.back_service.Token.update(v);this.forceUpdate(); });
	}

    updateService(service) {
        if(service)
            this.calculateHeaders(service);
    }

    setFilters(filters) {
        if(filters) {
            this.back_service.Filters.update(filters);
        }
        this.filters = filters;
        this.forceUpdate();
    }

    buildFilters(headers) {
        let filters = [];
        for (var i in headers) {
            if( headers[i].filter ) {
                filters.push(headers[i].filter);
            } 
        }
        return filters;
    }
    calculateHeaders(service, test) {
        service.model().then((model) => {
            let headers = {};
            let formHeaders = {};
            for (var name in model) {
                if(model[name].disabled) continue;
                let f = {
                    Name: model[name].Name,
                    type: model[name].type,
                    required: !model[name].nullable,
                    fieldName: name,
                    filter: model[name].Filter
                };
                if(!name.includes("_id") 
                && !(
                    (model[name].Filter && model[name].Filter.type === "editor") 
                 || (model[name].type === "timestamp")))
                    headers[model[name].Name || name] = f;
                formHeaders[model[name].Name || name] = f;
            }
            this.formHeaders = formHeaders;
            this.headers = headers;
            return headers;
        }).then((headers) => {
            if(!this.filters)
                this.filters = this.buildFilters(headers);
            this.forceUpdate();
        })
    }

	render() {
        let service = this.back_service.Service.value;
        return  <div>
            <ListModule TableHeaders={this.headers} TableClass={"striped centered"} LiveEdit={this.LiveEdit.value}
                            FormHeaders={this.formHeaders}
                            perPage={this.perPage.value} service={service} 
                            filterStyle={{ }} filterClassName={"grey lighten-5"}
                            FilterInput={this.filters} onFilters={(filters) => this.setFilters(filters)}/>
            {super.render()}
        </div>;
	}
}

CrudListPackage.Inputs = {
    RouterDependable: {
        type: Module.Types.Boolean,
        defaultValue: false
    },
    TableName: {
        type: Module.Types.Text,
        defaultValue: "products"
    },
	perPage: {
		type: Module.Types.Number,
        defaultValue: 2
	},
	TableHeaders:{
        type: Module.Types.Object,
        defaultValue:{
            "Id" : "id",
            "Name" : "name",
            "Value": "price"
        }
    },
    LiveEdit:{
        type: Module.Types.Boolean,
        defaultValue: false
    },
    Token : {
        type: Module.Types.Text,
        defaultValue: '123123'
    }
}

CrudListPackage.Outputs = {
}

CrudListPackage.Category = "NikatlasPackages";
CrudListPackage.EditPosition = "center";
export default CrudListPackage;
