import { AbstractMapWithMarkers } from '../abstract-map-with-markers';

/**
 * Small layer that handles common functionality of static maps (e.g. rendering an image)
 * that allows easier implementation of static maps as these only have to generate image
 * urls now.
 *
 * @abstract
 */
export class AbstractStaticMap extends AbstractMapWithMarkers {

    /**
     * @param {Marker[]} markers
     * @param {Object} size
     * @return {string}
     * @protected
     * @abstract
     */
    // eslint-disable-next-line
    imageUrl (markers, size) {
        throw new Error('This method must be implemented in subclasses');
    }

    async initialize () {
        if (this.node.nodeName.toLowerCase() === 'picture') {
            this.picture = this.node;
        } else {
            this.picture = document.createElement('picture');
            this.node.appendChild(this.picture);
        }

        this.picture.setAttribute('class', 'block');

        if (!this.options.fallbackSize) {
            this.options.fallbackSize = Object.assign({}, this.options.srcSet[0] || {});
        }

        this.options.fallbackSize.width = this.options.fallbackSize.width || 800;
        this.options.fallbackSize.height = this.options.fallbackSize.height || 600;
    }

    /**
     * @param {Marker[]} markers
     * @protected
     */
    render(markers) {
        for (const set of this.options.srcSet) {
            const source = document.createElement('source');
            source.setAttribute('srcset', this.imageUrl(markers, set));
            if (set.query) {
                source.setAttribute('media', set.query);
            }
            this.picture.appendChild(source);
        }

        // Fallback image
        this.image = document.createElement('img');
        this.picture.appendChild(this.image);
        this.image.setAttribute('class', 'block w-full');
        this.image.setAttribute('src', this.imageUrl(markers, this.options.fallbackSize));
    }

    prepareOptions (options) {
        options = super.prepareOptions(options);
        options.zoom = options.zoom || 85;
        options.srcSet = options.srcSet || [];

        return options;
    }


}
