import React, { useCallback } from 'react';
import { head, pathOr } from 'ramda';
import { klona } from 'klona';

// components
import { useStoreValue } from '../../../../../../store';
import { InputSwitch } from 'primereact/inputswitch';

const ElementSettingReportEnable = ({ setting = {}, setDataFn }) => {
    const chosenFieldSettings = useStoreValue('chosenFieldSettings');

    const handleChangeFn = useCallback((value) => {
        setDataFn(setting.name, value);
        const tableColumns = head(chosenFieldSettings.filter(o => o.name === 'table_columns'));
        let reportColumns = head(chosenFieldSettings.filter(o => o.name === 'reportColumns'));

        if (tableColumns) {
            if (reportColumns) {
                if (reportColumns.value && reportColumns.value.length === 0) {
                    const settingReports = head(chosenFieldSettings.filter(o => o.name === 'reportColumns'));
                    const settingData = pathOr([], ['value', 'stateFieldData'], tableColumns);
                    const settingReportData = pathOr([], ['value'], settingReports);
                    const canBeEnabled = settingData.filter(o => o.predefined).length > 0;
                    reportColumns.value = settingData.map((o) => {
                        const existing = pathOr({}, [], head(settingReportData.filter(s => s.name === o.name)));
                        const existingEnabled = pathOr(false, ['enableCsv'], existing);
                        return {
                            ...o,
                            ...existing,
                            predefined: o.predefined,
                            enableCsv: !canBeEnabled ? false : existingEnabled
                        }
                    });
                }

                const newValueReportColumns = klona(reportColumns.value).map(o => {
                    o.enableCsv = value
                    return o;
                });

                setDataFn('reportColumns', newValueReportColumns);
            }
        }
    }, [chosenFieldSettings]);

    return (
        <InputSwitch
            checked={setting.value}
            onChange={(e) => handleChangeFn(e.value)}/>
    );
}

export default ElementSettingReportEnable;