import get from 'lodash/get';
import isArray from 'lodash/isArray';
import { getUrl } from '../../../Utils/getUrl';
import { isEditableVectorImage } from '../../../Reducers/ImageGallery/Selectors';
import { getSvgContent, applySvgContentOperations } from '../../../Services/DesignDataService';

export const calculateScaleFactor = imageData => {
    const ow = get(imageData, 'original.width', 0);
    if (ow > 0) {
        const pw = get(imageData, 'preview.width', 0);
        return ow / pw;
    }
    return 1;
};

export const fixSrcURL = src => getUrl(src);

export const getRasterURL = imageURL => ('' + imageURL).replace(/svg$/, 'png');

export const isOriginalVector = imageData =>
    /^(eps|ept|ps|pdf|ai|svg)$/i.test(get(imageData, 'original.format', ''));

export const noCache = src => `${src}?${Math.random()}`;

export const prepareImageObjectData = rawObject => {
    const { imageData: image } = rawObject;
    const data = {
        ...rawObject,
        scaleFactor: calculateScaleFactor(image),
        src: fixSrcURL(rawObject.src),
    };

    data.transformImageSrc = async (url, { operations } = {}) => {
        if (!isEditableVectorImage({ url })) {
            return noCache(url);
        }

        const { displayColorPreview, gallery, isPlaceHolderImage } = image;
        const originalVector = isOriginalVector(image);

        if (!originalVector && !displayColorPreview && !gallery && !isPlaceHolderImage) {
            return noCache(fixSrcURL(getRasterURL(get(image, 'preview.url', ''))));
        }

        const svgContent = await getSvgContent(url, true);

        return applySvgContentOperations(
            image.original,
            image.preview,
            displayColorPreview || gallery || originalVector
                ? operations
                    ? operations
                    : image.operations
                : null,
            svgContent
        );
    };

    return data;
};

export const prepareObjectData = rawObject =>
    rawObject && rawObject.imageData ? prepareImageObjectData(rawObject) : rawObject;

export const prepareCanvasData = (canvasData, prepareObjectDataFn = prepareObjectData) => {
    if (typeof canvasData === 'object') {
        const { objects, ...otherProps } = canvasData;
        const result = { ...otherProps };
        if (isArray(objects)) {
            result.objects = objects.map(prepareObjectDataFn);
        }
        return result;
    }
    return canvasData;
};
