import React from 'react';
import PropTypes from 'prop-types';
import { Source } from '@storybook/addon-docs/blocks';
import { jsonToFormattedString } from './stringTools';
import { INPUT, TEXTAREA } from '../constants/schemaComponentTypes';


export const TableContentFromObject = ({ obj, keyHeader, valueHeader }) => (
    <>
        <thead>
            <tr>
                <th>{keyHeader}</th>
                <th>{valueHeader}</th>
            </tr>
        </thead>
        <tbody>
            {
                Object.keys(obj).map(key => (
                    <tr key={key}>
                        <td>{key}</td>
                        <td>{obj[key]}</td>
                    </tr>
                ))
            }
        </tbody>
    </>
);

TableContentFromObject.propTypes = {
    keyHeader: PropTypes.string,
    valueHeader: PropTypes.string,
    obj: PropTypes.object.isRequired
};

TableContentFromObject.defaultProps = {
    keyHeader: 'Name',
    valueHeader: 'Description'
};

export const buildFormOutput = form => {
    const formOutput = {};
    Object.keys(form).forEach(settingKey => {
        const { defaultValue, type } = form[settingKey];
        if ((defaultValue !== undefined) && type) {
            formOutput[settingKey] = {
                value: defaultValue,
                type
            };
        }
        if (formOutput[settingKey] && (type === INPUT || type === TEXTAREA)) {
            formOutput[settingKey].isLocalized = true;
        }
    });
    return jsonToFormattedString(formOutput);
};

export const CollapsibleJsonSnippet = ({ summary, code }) => (
    <details>
        <summary>{summary}</summary>
        <Source language="json" code={jsonToFormattedString(code)} />
    </details>
);

CollapsibleJsonSnippet.propTypes = {
    summary: PropTypes.string,
    code: PropTypes.any
};

CollapsibleJsonSnippet.defaultProps = {
    summary: 'summary',
    code: ''
};

export const FormOutput = ({ code }) => (
    <Source
        language="json"
        code={buildFormOutput(code)}
    />
);

FormOutput.propTypes = {
    code: PropTypes.any
};

FormOutput.defaultProps = {
    code: ''
};
