class KMLParser extends ol.format.KML {
    constructor(options) {
        super(options);
        this.base64Regex = /data:image\/(?:png|jpeg|webp|svg\+xml)(?:;charset=utf-8)?;base64,((?:[A-Za-z0-9_-]|[+/])+={0,2})/gim;
    }

    getType() {
        return "text";
    }

    readFeature(source, options) {
        return super.readFeature(this.handleBadTags(source), options);
    }

    readFeatures(source, options) {
        return super.readFeatures(this.handleBadTags(source), options);
    }

    handleBadTags(rawString) {
        let result = rawString;
        result = rawString.replace(
            /<.*?cascadingstyle.*?>\s*(<styleurl>.*<\/styleurl>)/gim,
            (a, b) => {
                return a.slice(0, a.indexOf(b));
            }
        );
        result = result.replace(
            /<.*?cascadingstyle.*?kml:id="(.+)">\s*<style>/gim,
            (a, b) => {
                return `<Style id="${b}">`;
            }
        );
        result = result.replace(/<\/Style>\s*<\/.*?cascadingstyle>/gim, "</Style>");
        result = result.replace(this.base64Regex, (a, b) => {
            const withPadding =
                b.length % 4 !== 0
                    ? (a += Array.from({ length: 4 - (b.length % 4) }, () => "=").join(
                        ""
                    ))
                    : a;
            return withPadding.replaceAll("-", "+").replaceAll("_", "/");
        });
        return result;
    }
}
