import $ from 'jquery';
import Helper from "./Helper";

const helper = new Helper();
export function applyDynamicStyles($fields) {
    $fields.each(function () {
        const $field = $(this);
        const Property = $field.data('property') ?? '';
        let unit = $field.data('unit') ?? '';
        let value = $field.val() ?? '';
        if ($field.is(':radio')) {
            value = $fields.filter(`[name="${$field.attr('name')}"]:checked`).val() ?? '';
        }
        if ($field.is(':checkbox')) {
            value = $fields.filter(`[name="${$field.attr('name')}"]:checked`).val() ?? '';
        }

        const target = $field.data('target');
        const defaultValue = $field.data('default-value') ?? '';
        const dependedTarget = $field.data('depended-target-value') ?? '';
        const targetColorA = $field.data('target-color-a') ?? '';
        const directValueChecked = $field.data('direct-value-checked') ?? '';
        const directValueUnchecked = $field.data('direct-value-unchecked') ?? '';


        if( targetColorA ){
            const aChannel = $(targetColorA).val() ?? '';
            value = helper.hexToRgba(value,aChannel);
        }
        if( dependedTarget ){
            const $dependedTarget = $(dependedTarget);
            let dependedValue = '';
            if( $dependedTarget.is(':radio')){
                dependedValue = $dependedTarget.filter(':checked').val() ?? '';
            }else{
                dependedValue = $(dependedTarget).val() ?? '';
            }
            if( dependedValue ){
                unit = dependedValue;
            }
        }

        if (value !== null && value !== '' && Property !== null && Property !== '') {
            const properties = Property.split(',').map(prop => prop.trim());
            properties.forEach(prop => {
                $('body').find(target).css(prop, value + unit);
            });
        }else if(defaultValue !== '' && value === '' && Property !== '' ) {
            const props = Property.split(',').map(prop => prop.trim());
            props.forEach(prop => {
                $('body').find(target).css(prop, defaultValue + unit);
            });
        }
        if( $field.is(':checkbox') && Property && directValueChecked && directValueUnchecked ){
            if(value){
                $('body').find(target).css(Property, directValueChecked + unit);
            }else{
                $('body').find(target).css(Property, directValueUnchecked + unit);
            }
        }

    });
}