import { text, boolean, select, color, radios, optionsKnob, number, object } from '@storybook/addon-knobs';
import { INPUT, TOGGLE, TOGGLE_CHECK, TEXTAREA, COLORPICKER, DROPDOWN, RADIO, CHECKBOX, SLIDER, IMAGE_UPLOADER } from '../constants/schemaComponentTypes';

const parseLocalizedKey = (key = '') => {
    if (key && key.includes('uieditor.sfbComponent')) {
        const keyArray = key.split('.');

        if (keyArray && keyArray.length) {
            return keyArray[keyArray.length - 2];
        }
    }

    return key;
};

const settingToKnob = ({ title, type, defaultValue, labelOn, label, options }) => {
    const titleParsed = parseLocalizedKey(title);
    switch (type) {
        case INPUT:
        case TEXTAREA:
            return text(titleParsed, parseLocalizedKey(defaultValue) || defaultValue);
        case TOGGLE:
            return boolean(parseLocalizedKey(labelOn), defaultValue);
        case TOGGLE_CHECK:
            return boolean(parseLocalizedKey(label), defaultValue);
        case COLORPICKER:
            return color(titleParsed, defaultValue);
        case DROPDOWN:
            return select(titleParsed, options.map(({ value }) => value), defaultValue);
        case RADIO:
            return radios(titleParsed, options.map(({ value }) => value), defaultValue);
        case CHECKBOX: {
            const valuesObj = {};
            options.forEach(({ value }) => {
                valuesObj[value] = value;
            });
            return optionsKnob(titleParsed, valuesObj, defaultValue, { display: 'check' });
        }
        case SLIDER:
            return number(titleParsed, defaultValue, options);
        case IMAGE_UPLOADER:
            return object(titleParsed, defaultValue);
        default:
            return undefined;
    }
};

export const getKnobs = (form = []) => {
    const knobs = {};
    Object.keys(form).forEach(settingKey => {
        const knobValue = settingToKnob(form[settingKey]);
        if (typeof knobValue === 'boolean' || settingToKnob(form[settingKey])) {
            knobs[settingKey] = settingToKnob(form[settingKey]);
        }
    });
    return knobs;
};
