import React from 'react';

import { OptionalSection } from 'lib/components';

import validator from 'lib/validator';
import messages from './messages.js';
import commonMessages from '../../messages.js';

import { num } from 'lib/num';

export const exchangeRateFields = ["currency", "currencySymbol", "exchangeRateDate", "exchangeRate", "exchangeRateSource"];

export const validateExchangeRate = (obj, error) => {
    let valid = true;

    if (!error || !obj) {
        //nothing to do
        return valid;
    }

    if (!validator.required(obj.currency)) {
        error({ field: "currency", code: commonMessages.validationFieldRequired.id })
        valid = false;
    }
    if (!validator.required(obj.currencySymbol)) {
        error({ field: "currencySymbol", code: commonMessages.validationFieldRequired.id })
        valid = false;
    }

    if (obj.enableExchangeRate) {
        if (!validator.required(obj.exchangeRate)) {
            error({ field: "exchangeRate", code: commonMessages.validationFieldRequired.id })
            valid = false;
        } else if (!validator.decimal(obj.exchangeRate)) {
            error({ field: "exchangeRate", code: commonMessages.validationFieldDecimal.id })
            valid = false;
        }
    }

    return valid;
}


export default ({ form, fieldProps, intl, valueOf, onChangeHandler, disabled, i18n, unitCurrency, unitCurrencySymbol, className, dateField, errors }) => {
    let 
        enableExchangeRate = valueOf("enableExchangeRate"),
        exchangeRateDate = valueOf("exchangeRateDate"),
        reversed = valueOf("__exchangeRate_reverse"),
        reverseExchangeRate = valueOf("__exchangeRate_reversedRate"),
        exchangeRate = valueOf("exchangeRate"),
        date = dateField ? valueOf(dateField) : null;

    fieldProps = fieldProps ? { ...fieldProps, required: true } : { required: true };

    let 
        rateFields = null,
        reverseButton = <button type="button" onClick={ onChangeHandler("__exchangeRate_reverse", () => !reversed) }> &lt;--&gt; </button>;

    if (reversed) {
        rateFields = (
            <div className="row row-margin-10">
                <div className="col-sm-4">
                    { form.renderMoneyField("__exchangeRate_reversedRate", "", valueOf("currencySymbol"), valueOf("currency"), { ...fieldProps, className: "big", onChange: reversedHandler("__exchangeRate_reversedRate", "exchangeRate", onChangeHandler), errors: errors && errors.exchangeRate }) }
                </div>
                <div className="col-sm-4">
                    { reverseButton }
                </div>
                <div className="col-sm-4">
                    { form.renderMoneyField("exchangeRate_constant_one", "", unitCurrencySymbol, unitCurrency, { ...fieldProps, className: "big", value: 1, disabled: true }) }
                </div>
            </div>
        );

    } else {
        rateFields = (
            <div className="row row-margin-10">
                <div className="col-sm-4">
                    { form.renderMoneyField("exchangeRate_constant_one", "", valueOf("currencySymbol"), valueOf("currency"), { ...fieldProps, className: "big", value: 1, disabled: true }) }
                </div>
                <div className="col-sm-4">
                    { reverseButton }
                </div>
                <div className="col-sm-4">
                    { form.renderMoneyField("exchangeRate", "", unitCurrencySymbol, unitCurrency, { ...fieldProps, className: "big", onChange: reversedHandler("exchangeRate", "__exchangeRate_reversedRate", onChangeHandler) }) }
                </div>
            </div>
        );
    }

    return (
        <div className={ className }>
            <div className="row row-margin-10">
                <div className="col-xs-6 p10">
                    { form.renderField("currency", intl.formatMessage(messages.currency), fieldProps) }
                </div>
                <div className="col-xs-6 p10">
                    { form.renderField("currencySymbol", intl.formatMessage(messages.currencySymbol), fieldProps) }
                </div>
            </div>

            <div>
                <OptionalSection 
                    checked={ enableExchangeRate } 
                    className="pv10"
                    onStatusChange={ onChangeHandler("enableExchangeRate", v => v, (value, values) => {
                        let exchangeRateDate = values.get("exchangeRateDate");
                        if (value) {
                            values = values.delete("currency").delete("currencySymbol");
                            if (!exchangeRateDate && date) {
                                values = values.set("exchangeRateDate", date);
                            }
                        } else {
                            values = values
                                .set("currency", unitCurrency)
                                .set("currencySymbol", unitCurrencySymbol)
                                .delete("exchangeRate")
                                .delete("exchangeRateSource")
                                .delete("exchangeRateDate")
                                .delete("__exchangeRate_reversedRate")
                                .delete("__exchangeRate_reverse");
                        }
                        return values;
                    }) }
                    title={ intl.formatMessage(messages.enableExchangeRate) }
                    disabled={ disabled }
                    >
                    { rateFields }
                    <div className="row row-margin-10">
                        <div className="col-xs-6 p10">
                            { form.renderDateField("exchangeRateDate", intl.formatMessage(messages.exchangeRateDate), fieldProps) }
                        </div>
                        <div className="col-xs-6 p10">
                            { form.renderField("exchangeRateSource", intl.formatMessage(messages.exchangeRateSource), fieldProps) }
                        </div>
                    </div>
                </OptionalSection>
            </div>
        </div>
    );

}



function reverse(val, def) {
    if (val == 0) {
        return 0;
    }
    if (!val || isNaN(val)) {
        return typeof def == "undefined" ? val : def;
    }
    return num(1 / val, 6);
}


function reversedHandler(field, fieldReversed) {
    return function(value, values) {
        return values.set(field, value).set(fieldReversed, reverse(value));
    };
} 

