import * as React from 'react';
import { ValidationState } from '../../models/Validation';
import { validationOnInit, validation } from '../../utils/helper';
import validationRules from '../../utils/validationRules';
import { ValidationRule } from '../../models/Validation';
import { Colors } from '../../models/colors';
export interface CheckboxProps {
	checked?: boolean;
	name?: string;
	validationRules?: Array<ValidationRule>;
	required?: boolean;
	palette?: Colors;
	id?: string;
	label?: HTMLElement;
	valid?: ValidationState;
	automationName?: string;
	disabled?: boolean;
	notifyValidity?: (name: string, state: ValidationState, errorMessage?: string) => void;
	onChange?: (name: string, value: boolean) => void;
	translator?: Function;
}

type CheckboxContainer = CheckboxProps & {
	render: (onChange: () => void) => JSX.Element;
};

class Checkbox extends React.PureComponent<CheckboxContainer> {
	constructor(props: CheckboxContainer) {
		super(props);
		let assignedValidationRules = Object.assign([], this.props.validationRules || []);

		if (this.props.required) {
			assignedValidationRules.unshift({ name: 'required' });
		}

		if (this.props.notifyValidity) {
			let { name, state, errorMessage } = validationOnInit(
				validationRules,
				assignedValidationRules,
				this.props.name,
				this.props.checked,
				this.props.translator
			);
			this.props.notifyValidity(name, state, errorMessage);
		}
	}

	onChange = () => {
		let assignedValidationRules = Object.assign([], this.props.validationRules || []);
		if (this.props.required) {
			assignedValidationRules.unshift({ name: 'required' });
		}
		if (this.props.notifyValidity) {
			let { name, state, errorMessage } = validation(
				validationRules,
				assignedValidationRules,
				!this.props.checked,
				this.props.name,
				this.props.translator
			);
			this.props.notifyValidity(name, state, errorMessage);
		}
		this.props.onChange(this.props.name, !this.props.checked);
	};

	render() {
		return this.props.render(this.onChange);
	}
}

export default Checkbox;
