/*
    SlotStyles
*/

class SlotStyleItem extends React.Component {
    constructor(props) {
        super(props);
        console.log('AAA SlotStyleItem constructor = ', this.props.data);
        this.state = {
            name: this.props.data[0],
            value: this.props.data[1],
        };
        this.onInputChange = this.onInputChange.bind(this);
    };
    onInputChange(e){
        const name = e.target.name;
        this.setState({[name]: e.target.value});
        this.props.editStyle([name, e.target.value], this.props.index);
    };
    remove = () => {
        this.props.deleteStyle(this.props.index);
    };
    render() {
        const {name, value} = this.state;
        return (
            <div className="styles-field-item">
                <input ref="newName" type="text" className="form-control name"  name="name" onChange={this.onInputChange} value={name} placeholder="поле" />&nbsp;
                <input ref="newValue" type="text" className="form-control value" name="value" onChange={this.onInputChange} value={value} placeholder="значение" />
                <div className="delete-styles-field" onClick={this.remove}>&#215;</div>
            </div>
        );
    }
}

class SlotStyles extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            styles: [],
            count: 0
        };
        
        var j = 0;
        if (this.props.data) {
            Object.keys(this.props.data).map(name => this.state.styles.push([name, this.props.data[name], j++]));
            this.state.count = this.state.styles.length;
        }
        this.deleteStyle = this.deleteStyle.bind(this);
    };
    addStyle = () => {
        var {styles, count} = this.state;
        styles.push(['', '', count]);
        this.setState({styles: styles, count: count + 1});
        this.props.editStyles(this.state.styles);
    };
    deleteStyle = (i) => {
        var stylesList = this.state.styles;
        stylesList.splice (i, 1);
        this.setState({styles: stylesList});
        this.props.editStyles(this.state.styles);
    };
    editStyle = (item, i) => {
        if (item[0] == 'name') {
            this.state.styles[i][0] = item[1];
        } else {
            this.state.styles[i][1] = item[1];
        }
        this.props.editStyles(this.state.styles);
    };
    eachStyle = (item, i) => {
        return (
            <SlotStyleItem key={'k'+item[2]} index={i} data={item} deleteStyle={this.deleteStyle} editStyle={this.editStyle} />
        );
    };
    render() {
        return(
            <div className="form-group styles">
                <span className="title">styles:</span>
                {this.state.styles.map(this.eachStyle)}
                <span className="add-styles" onClick={this.addStyle}>Добавить аттрибут</span>
            </div>
        );
    }
}
