import { createHash } from 'crypto';
import { HttpHeader } from '@linzjs/lambda';
import { basename } from 'path';
export const TileEtag = {
    // To force a full cache invalidation change this number
    RenderId: 1,
    key(object) {
        return createHash('sha256').update(JSON.stringify(object)).digest('base64');
    },
    /** Generate a unique ETag for this tile */
    generate(compositions, xyzData) {
        // We cannot serialize the CogTiff inside of composition so replace it with the source name
        const layers = compositions.map((c) => {
            return { ...c, tiff: basename(c.tiff.source.uri) };
        });
        const xyz = { ...xyzData, tileMatrix: xyzData.tileMatrix.identifier };
        return TileEtag.key({ xyz, layers, RenderId: TileEtag.RenderId });
    },
    isNotModified(req, cacheKey) {
        // If the user has supplied a IfNoneMatch Header and it contains the full sha256 sum for our
        // etag this tile has not been modified.
        const ifNoneMatch = req.header(HttpHeader.IfNoneMatch);
        if (ifNoneMatch != null && ifNoneMatch.indexOf(cacheKey) > -1) {
            req.set('cache', { key: cacheKey, hit: true, match: ifNoneMatch });
            return true;
        }
        return false;
    },
};
