const fs = require('fs');
var path = require('path');
const zlib = require('zlib');

String.prototype.splice = function (idx, rem, str) {
    return this.slice(0, idx) + str + this.slice(idx + Math.abs(rem));
};

const color = ['grey', 'red', 'green', 'blue']

exports.BoardCard = (card, next) => {
    filepath = path.join(process.cwd(), 'Cards', card.nme + '.svg')
    fs.readFile(filepath, 'utf8', function (err, source) {
        if (err) {
            throw err;
        }

        if (card.sym > 0) {
            const cir = '<circle cx="0" cy="0" r="70" stroke="clrX" stroke-width="12" fill="clrX" fill-opacity="0.5" />'
            let coin = cir.replace(/clrX/g, color[card.sym])
            let x = String(source).indexOf('</svg>')
            source = source.splice(x, 0, coin);
        }

        if (card.cls > 0) {
            let crs = '<path d="M -70,-60 70,60 z m 1,120 -1,1 140,-120 -1,1" style="stroke:clrX;stroke-width:32;stroke-linejoin:round" />'
            let chk = crs.replace(/clrX/g, color[card.sym])
            let x = String(source).indexOf('</svg>')
            source = source.splice(x, 0, chk);
        }

        var buff = Buffer.from(JSON.stringify({ inx: card.inx, crd: card.crd, img: source }))
        zlib.gzip(buff, function (_, squished) {
            next(null, squished);
        });
    })
}

exports.DealtCard = (card, next) => {
    filepath = path.join(process.cwd(), 'Cards', card.nme + '.svg')
    fs.readFile(filepath, 'utf8', function (err, source) {
        var buff = Buffer.from(JSON.stringify({ inx: card.inx, dlr: card.dlr, img: source }))
        zlib.gzip(buff, function (_, squished) {
            next(null, squished);
        });
    })
}

exports.getSvg = (card, res) => {
    filepath = path.join(process.cwd(), 'Cards', card + '.svg')
    fs.readFile(filepath, 'utf8', function (err, source) {
        res.setHeader('Content-type', 'image/svg+xml');
        res.end(source);
    })
}