import { Alert } from 'lib/components';

import { FormattedMessage } from 'react-intl';

export PeriodTitle from './PeriodTitle';
export { getPeriodParams } from './PeriodTitle';

export { saveParam } from './redux';

import messages from './messages.js';
import { formatDate } from 'lib/i18n';


export const periodCheckDecorator = (submitFn, config) => {
    let { period, date, periodParams, intl, dateType, i18n } = config;



    let 
        fdate = formatDate(date, i18n),
        fdateFrom = formatDate(periodParams.from, i18n),
        fdateTo = formatDate(periodParams.to, i18n),

        title = config.title || translate(intl, messages.dateAlertTitle, 'Warning'), 
        text = config.text || translate(intl, messages.dateAlertText, 'You are about to save a record with date ' + fdate + ' which is outside selected period ' + fdateFrom + ' - ' + fdateTo + '. The record will be saved, however it might not be visible on the current list. Do you want to continue?', { fdate, fdateFrom, fdateTo }), 
        yesLabel = config.yesLabel || translate(intl, messages.dateAlertYes, 'Yes, save the record'), 
        noLabel = config.noLabel || translate(intl, messages.dateAlertNo, 'No, I want to change the date');
    
    if (!periodParams || !date) {
        return submitFn();
    }

    if (date >= periodParams.from && date <= periodParams.to) {
        return submitFn();    
    }
    
    Alert.alert(title, text, [{ onPress: () => alert, text: noLabel }, { onPress: submitFn, text: yesLabel, primary: true }]);
}

function translate(intl, message, defaultMessage, data) {
    if (!intl) {
        return defaultMessage;
    }
    return intl.formatMessage(message, data);
}



export function injectPeriodParams(fn, key = "periodParams") {
    return (state) => {
        let unit = state && state.get && state.getIn(["params", "period"]);
        unit = unit ? unit.toJS() : {};
        let s = {
            [key]: unit,
            ...fn(state)
        };
        return s;
    }
}