import * as React from 'react';
import FormContext from "../Form/FormContext";
import * as uuidv4 from 'uuid/v4';
import {isEmpty, isString} from 'lodash';
interface FormComponentState {
    // id?: string
}

export default abstract class FormComponent<Props = {}, State extends FormComponentState = {}> extends React.Component<Props, State> {

    static contextType = FormContext;
    public defaultId: string;

    constructor(props:any) {
        super(props);
        this.defaultId = uuidv4();

    }


    componentWillReceiveProps(nextProps: any) {
        // const {value} = this.props;
        // console.log('---', nextProps)

        if (nextProps !== this.props) {

        }

    }

    validate(val?: string, errMsg?: string) {

        let msg = this.context.messages.filter((item: any) => item.id === this.defaultId);
        let errorMessage = msg.length ? msg[0].messages : '';
        if (errMsg) errorMessage = errMsg;
        let stateErrorMessage = !isEmpty(val) ? '' : errorMessage;

        this.props['validate'] && this.context.validate(
            this.defaultId,
            !isEmpty(val)
                ? val
                : '',
            this.props['validate'],
            stateErrorMessage,
            !this.props['disabled'],
            this.props['name'] || this.defaultId
        );

    }

    error() {
        let businessErrorMessage:string = this.props['errorMessage'] || '';

        if (this.context.click) {
            let msg = this.context.messages.filter((item: any) => item.id === this.defaultId);

            if (businessErrorMessage) {
                return businessErrorMessage
            } else {
                return msg.length ? msg[0].messages : null
            }
        }

        return ''
    }

    /*size() {
        let componentSize: string = `${this.props['size'] || 'medium'}-ui`;
        if (this.context.size) {
            componentSize = `${this.context.size}-ui`
        }

        return componentSize

    }*/

    size() {
        let componentSize: string = `is-${this.props['size'] || 'large'}`;
        if (this.context.size) {
            componentSize = `is-${this.context.size}`
        }

        return componentSize

    }

    iconRight() {
        let icon = this.props['icon'];
        const tempIconRight: any = isString(icon) ? [{icon: icon, position: 'left'}] : icon;
        return icon && tempIconRight.filter((item: any) => item.position === 'right').length
    }

    iconLeft() {
        let icon = this.props['icon'];
        const tempIconLeft: any = isString(icon) ? [{icon: icon, position: 'left'}] : icon;
        return icon && tempIconLeft.filter((item: any) => item.position === 'left').length
    }

    readOnly() {
        let componentLoading: any = this.props['readOnly'];

        if (this.context.loading) {
            componentLoading = this.context.loading
        }

        return componentLoading
    }
}