import React from 'react';

require('./ToggleButtons.scss');


function onClick(values, value, onChange) {
    return (e) => {
        e.preventDefault();
        e.stopPropagation();

        if (typeof onChange === "function") {
            if (values[value]) {
                delete values[value];
            } else {
                values[value] = true;
            }
            onChange(Object.keys(values));
        }
    }
}


export default ({ options, value, size, onChange, labelKey = "label", valueKey = "value" }) => {
    if (!Array.isArray(options) || !options.length) {
        return null;
    }

    let values = {};
    if (Array.isArray(value)) {
        for (let i = 0; i < value.length; i++) {
            values[value[i]] = true;
        }
    } else {
        values[value] = true;
    }

    return (
        <div className="ToggleButtons">
            { options.map((opt, key) => {
                    return <button className={ values[opt[valueKey]] ? "selected" : "" } key={ opt[valueKey] || `_empty_${key}` } onClick={ onClick(values, opt[valueKey], onChange) }>{ opt[labelKey] }</button>
                }) 
            }
        </div>
    );
}

/*
key={ id } options={ items } value={ value } onChange
*/