var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
import { toString as uint8ArrayToAsciiString } from 'uint8arrays/to-string';
import isSvg from 'is-svg';
import { getResponseResult } from './stream';
import { serializeError } from 'serialize-error';
const PATTERN_IPFS_HASH = /^Qm[a-zA-Z0-9]{44}$/g;
const PATTERN_HTTP = /^https:\/\/|^http:\/\//g;
function createObjectURL(rawData, type) {
    const blob = new Blob([rawData], { type });
    return URL.createObjectURL(blob);
}
function createImgData(rawData, type) {
    const imgBase64 = uint8ArrayToAsciiString(rawData, 'base64');
    const file = `data:${type};base64,${imgBase64}`;
    return file;
}
export const detectContentType = (mime) => {
    if (mime) {
        if (mime.includes('video')) {
            return 'video';
        }
        if (mime.includes('audio')) {
            return 'audio';
        }
    }
    return 'other';
};
const basic = /\s?<!doctype html>|(<html\b[^>]*>|<body\b[^>]*>|<x-[^>]+>)+/i;
function isHtml(string) {
    const newString = string.trim().slice(0, 1000);
    return basic.test(newString);
}
function shortenString(string, length = 300) {
    return string.length > length ? `${string.slice(0, length)}...` : string;
}
export const chunksToBlob = (chunks, mime) => new Blob(chunks, mime ? { type: mime } : {});
export const parseArrayLikeToDetails = (content, cid, onProgress) => __awaiter(void 0, void 0, void 0, function* () {
    var _a;
    try {
        const mime = (_a = content === null || content === void 0 ? void 0 : content.meta) === null || _a === void 0 ? void 0 : _a.mime;
        const response = {
            link: `/ipfs/${cid}`,
            gateway: false,
            cid,
        };
        const initialType = detectContentType(mime);
        if (['video', 'audio'].indexOf(initialType) > -1) {
            return Object.assign(Object.assign({}, response), { type: initialType });
        }
        const rawData = (content === null || content === void 0 ? void 0 : content.result)
            ? yield getResponseResult(content.result, onProgress)
            : undefined;
        if (!mime) {
            response.text = `Can't detect MIME for ${cid.toString()}`;
            response.gateway = true;
        }
        else if (mime.indexOf('text/plain') !== -1 ||
            mime.indexOf('application/xml') !== -1) {
            if (isSvg(Buffer.from(rawData).toString())) {
                response.type = 'image';
                response.content = createImgData(rawData, 'image/svg+xml');
            }
            else {
                const dataBase64 = uint8ArrayToAsciiString(rawData);
                response.link =
                    dataBase64.length > 42 ? `/ipfs/${cid}` : `/search/${dataBase64}`;
                if (dataBase64.match(PATTERN_IPFS_HASH)) {
                    response.gateway = true;
                    response.type = 'other';
                    response.content = dataBase64;
                    response.link = `/ipfs/${cid}`;
                }
                else if (dataBase64.match(PATTERN_HTTP)) {
                    response.type = 'link';
                    response.gateway = false;
                    response.content = dataBase64;
                    response.link = `/ipfs/${cid}`;
                }
                else if (isHtml(dataBase64)) {
                    response.type = 'other';
                    response.gateway = true;
                    response.content = cid.toString();
                }
                else {
                    response.type = 'text';
                    response.content = dataBase64;
                    response.text = shortenString(dataBase64);
                }
            }
        }
        else if (mime.indexOf('image') !== -1) {
            response.content = createImgData(rawData, mime);
            response.type = 'image';
            response.gateway = false;
        }
        else if (mime.indexOf('application/pdf') !== -1) {
            response.type = 'pdf';
            response.content = createObjectURL(rawData, mime);
            response.gateway = true;
        }
        return response;
    }
    catch (e) {
        const serializedError = serializeError(e);
        console.log('----parseRawIpfsData', JSON.stringify(serializedError, null, 2), cid);
        return undefined;
    }
});
export const contentToUint8Array = (content) => __awaiter(void 0, void 0, void 0, function* () {
    return new Uint8Array(typeof content === 'string'
        ? Buffer.from(content)
        : yield content.arrayBuffer());
});
export const createTextPreview = (array, mime, previewLength = 150) => {
    return array && mime && mime === 'text/plain'
        ? uint8ArrayToAsciiString(array).slice(0, previewLength)
        : undefined;
};
//# sourceMappingURL=content.js.map