import get from 'lodash/get';
import circleMaskSVG from '../../../Resources/Masks/circle.svg';
import { getConf } from '../../configuration';
import { getClientHighlightColor, getConfigurator, getItem } from '../Configurator/Selectors';
import { getSelectedDesignArea, getSelectedDesignProductionMethodForDesignArea } from './Selectors';

const maskTypes = {
    circle: 'circle',
    freeForm: 'freeForm',
};

const getMaskIfComplete = obj =>
    maskTypes[get(obj, 'mask.maskType')] && {
        ...obj.mask.maskData,
        type: obj.mask.maskType,
        dataUrl: obj.mask.maskDataUrl,
        source: obj,
    };

export const designAreaAppliesMask = (state, designArea) => {
    if (!designArea) {
        designArea = getSelectedDesignArea(state);
    }
    const designProductionMethod = getSelectedDesignProductionMethodForDesignArea(state, designArea);
    return !!(getMaskIfComplete(designProductionMethod) || getMaskIfComplete(designArea));
};

const createMaskSrc = ({ itemIdentifier, designAreaIdentifier, designProductionMethodIdentifier, type }) => {
    switch (type) {
        case maskTypes.circle: {
            return circleMaskSVG;
        }
        case maskTypes.freeForm: {
            const fileName = designProductionMethodIdentifier
                ? `${designAreaIdentifier}_${designProductionMethodIdentifier}`
                : designAreaIdentifier;
            return `${getConf('network.host')}/designer/masks/${itemIdentifier}/${fileName}.svg`;
        }
        default: {
            return false;
        }
    }
};

export const getMaskDataForDesignArea = (state, designArea = null) => {
    if (!designArea) {
        designArea = getSelectedDesignArea(state);
    }
    const designProductionMethod = getSelectedDesignProductionMethodForDesignArea(state, designArea);
    const item = getItem(getConfigurator(state));
    const maskData = getMaskIfComplete(designProductionMethod) || getMaskIfComplete(designArea);
    if (maskData) {
        const src =
            maskData.dataUrl ||
            createMaskSrc({
                itemIdentifier: item.identifier,
                designAreaIdentifier: designArea.identifier,
                designProductionMethodIdentifier:
                    maskData.source === designProductionMethod ? designProductionMethod.identifier : false,
                type: maskData.type,
            });
        return { ...maskData, src, outlineColor: getClientHighlightColor(state) };
    }
    return false;
};
