'use strict';

import React from 'react';
import PropTypes from 'prop-types';
import _ from 'lodash';
import {Checkbox} from '../../form/Checkbox';

export class ListControlCheckbox extends React.Component {
    static contextTypes = {
        listStore: PropTypes.object,
        form: PropTypes.object
    };

    static propTypes = {
        label: PropTypes.string,
        dependentFieldName: PropTypes.string.isRequired,
        ariaLabelledById: PropTypes.string,
        hiddenLabel: PropTypes.bool
    };

    static defaultProps = {
        label: 'TRANSLATE:SELECT_ALL',
        ariaLabelledById: null,
        hiddenLabel: true
    };

    getVisibleItems() {
        return this.context.listStore.getPrimaryKeys();
    }

    onChange() {
        let formRecords = this.context.form.value;
        let items = this.getVisibleItems();

        let checked = this.refs.input.getValue();

        let newFormValue = {};
        items.forEach(id => {
            newFormValue[id] = _.extend({}, formRecords[id], {
                [this.props.dependentFieldName]: checked
            });
        });

        this.context.form.setValue(newFormValue);
    }

    render() {
        let formRecords = this.context.form.value;
        let items = this.getVisibleItems();

        let checkboxValue = false;
        if (items.length > 0) {
            let selectedItems = items.filter(
                id => formRecords[id] && formRecords[id][this.props.dependentFieldName]
            );

            if (selectedItems.length === items.length) {
                checkboxValue = true;
            }

            if (selectedItems.length > 0 && selectedItems.length < items.length) {
                checkboxValue = null;
            }
        }

        return (
            <Checkbox
                aria-checked={checkboxValue === null ? 'mixed' : checkboxValue}
                checked={checkboxValue}
                hiddenLabel={this.props.hiddenLabel}
                disabled={items.length === 0}
                onChange={this.onChange.bind(this)}
                ref="input"
                label={this.props.label}
                groupClassName="rc-list-checkbox"
                aria-labelledby={this.props.ariaLabelledById}
                removeName
            />
        );
    }
}
