/*
 * NOTE: We want to customize the MarkerClusterer vendor script,
 * however it defines MarkerClusterer, Cluster and ClusterIcon but only exports
 * MarkerClusterer (if module is of type object), so we use imports-loader to set
 * module to false and to deactivate the export there, then we use exports-loader in
 * order to import the things we need to override but otherwise cant
 * import.
 *
 * More info at:
 * https://github.com/webpack-contrib/imports-loader
 * https://github.com/webpack-contrib/exports-loader
 *
 * Note: This approach is not compatible with markerclusterer 3.* and onwards
 * TODO Refactor into newer version of markerclusterer without hacks
 */
import {
    MarkerClusterer,
    ClusterIcon,
} from 'imports-loader?module=>false!exports-loader?MarkerClusterer,ClusterIcon!@google/markerclustererplus';


/**
 * We override this function because <tt>anchorIcon</tt> doesn't exist
 * in our custom version of ClusterIcon.
 *
 * @param {object} latlng
 * @returns {object}
 */
ClusterIcon.prototype.getPosFromLatLng_ = function getPosFromLatLng_(latlng) {
    const pos = this.getProjection().fromLatLngToDivPixel(latlng);
    pos.x = parseInt(pos.x, 10);
    pos.y = parseInt(pos.y, 10);
    return pos;
};

/**
 * We overide this function to customize the markup of a rendered cluster
 * and to add the backgroundColor only our custom version has.
 */
ClusterIcon.prototype.show = function show() {
    if (this.div_) {
        const pos = this.getPosFromLatLng_(this.center_);
        this.div_.style.cssText = this.createCss(pos);
        this.div_.style.color = this.cluster_.getMarkerClusterer().textColor || 'white';
        this.div_.style.backgroundColor = this.cluster_.getMarkerClusterer().backgroundColor || '#333';
        this.div_.style.zIndex = google.maps.Marker.MAX_ZINDEX + 1;
        this.div_.title = (typeof this.sums_.title === 'undefined' || this.sums_.title === '') ?
            this.cluster_.getMarkerClusterer().getTitle() :
            this.sums_.title;

        this.div_.innerHTML = `
            <span class="tb-map-marker-cluster__label">
                ${this.sums_.text}
            </span>
        `;

        this.div_.style.display = '';
    }

    this.visible_ = true;
};

/**
 * Add a function to set the background color of a cluster
 * which is not available by default.
 *
 * @param {string} color
 * @param {string} backgroundColor
 */
MarkerClusterer.prototype.setClusterColors = function(color, backgroundColor) {
    this.textColor = color;
    this.backgroundColor = backgroundColor;
};

export { MarkerClusterer };
