"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const path_1 = __importDefault(require("path"));
const IndexService_1 = __importDefault(require("../../src/index/IndexService"));
const Utils_1 = __importDefault(require("../Utils"));
const Datastore_1 = __importDefault(require("../../src/common/Datastore"));
const supertest_1 = __importDefault(require("supertest"));
const ErrorCode_1 = __importDefault(require("../../src/index/ErrorCode"));
const ipfs_core_1 = require("ipfs-core");
const IPFS = __importStar(require("ipfs-core"));
describe('IndexService', () => {
    let service;
    beforeAll(async () => {
        await Utils_1.default.initDatabase();
        service = new IndexService_1.default();
        const ipfs = await IPFS.create();
        service['ipfsClient'] = ipfs;
    });
    beforeEach(async () => {
        await Datastore_1.default.ScanningRequestModel.remove();
        await Datastore_1.default.GenerationRequestModel.remove();
    });
    describe('start', () => {
        it('should start the service', () => {
            const listen = spyOn(service['app'], 'listen');
            service.start();
            expect(listen).toHaveBeenCalledWith(7003, '0.0.0.0', jasmine.anything());
        });
    });
    describe('POST /create/:id', () => {
        it('should throw error if no dataset has not completed scanning', async () => {
            const scanningRequest = await Datastore_1.default.ScanningRequestModel.create({
                status: 'active',
                path: 'base/path'
            });
            const response = await ((0, supertest_1.default)(service['app']))
                .get(`/create/${scanningRequest.id}`);
            expect(response.status).toEqual(400);
            expect(response.body).toEqual({
                error: ErrorCode_1.default.SCANNING_INCOMPLETE
            });
        });
        it('should throw error if no dataset is provided', async () => {
            const response = await ((0, supertest_1.default)(service['app']))
                .get(`/create`);
            expect(response.status).toEqual(404);
        });
        it('should throw error if dataset id is invalid', async () => {
            const response = await ((0, supertest_1.default)(service['app']))
                .get(`/create/invalid_id`)
                .set('Accept', 'application/json');
            expect(response.status).toEqual(400);
            expect(response.body).toEqual({
                error: ErrorCode_1.default.DATASET_NOT_FOUND
            });
        });
        it('should throw error if dataset id does not exist', async () => {
            const response = await ((0, supertest_1.default)(service['app']))
                .get(`/create/507f1f77bcf86cd799439011`)
                .set('Accept', 'application/json');
            expect(response.status).toEqual(400);
            expect(response.body).toEqual({
                error: ErrorCode_1.default.DATASET_NOT_FOUND
            });
        });
        it('should return rootCid', async () => {
            const scanningRequest = await Datastore_1.default.ScanningRequestModel.create({
                status: 'completed',
                path: path_1.default.join('base', 'path')
            });
            await Datastore_1.default.GenerationRequestModel.create({
                datasetId: scanningRequest.id,
                status: 'completed',
                pieceCid: 'piece1',
                dataCid: 'data1',
                generatedFileList: [
                    {
                        path: path_1.default.join('a', 'b.mp4'),
                        selector: [0, 0],
                        size: 100,
                        start: 0,
                        end: 100
                    },
                    {
                        path: path_1.default.join('a', 'c.mp4'),
                        selector: [0, 1],
                        size: 100,
                        start: 0,
                        end: 50
                    },
                ]
            });
            await Datastore_1.default.GenerationRequestModel.create({
                datasetId: scanningRequest.id,
                status: 'completed',
                pieceCid: 'piece2',
                dataCid: 'data2',
                generatedFileList: [
                    {
                        path: path_1.default.join('a', 'c.mp4'),
                        selector: [0, 0],
                        size: 100,
                        start: 50,
                        end: 100
                    },
                    {
                        path: path_1.default.join('d', 'e.mp4'),
                        selector: [1, 0],
                        size: 100,
                        start: 0,
                        end: 100
                    },
                ]
            });
            const response = await ((0, supertest_1.default)(service['app']))
                .get(`/create/${scanningRequest.id}`)
                .set('Accept', 'application/json');
            expect(response.status).toEqual(200);
            const expectCid = 'bafyreigk3f2znurdgrmtjxemcegd5m7662aymxtzpkx7msobsb75f6xkya';
            expect(response.body).toEqual({
                rootCid: expectCid
            });
            const result = await service['ipfsClient'].dag.get(ipfs_core_1.CID.parse(expectCid));
            const expectedCidA = ipfs_core_1.CID.parse('bafyreidn23unhic76og5u3khw76i4fz7hhn5hdtvb7tmhzy3zqxkluw7tm');
            const expectedCidD = ipfs_core_1.CID.parse('bafyreigs4ma6yormosommvf44yrv2cniqtzaskln3zejyy5kvd4sexdgom');
            const expectedResult = {
                name: '',
                type: 'dir',
                entries: {
                    a: expectedCidA,
                    d: expectedCidD
                },
                sourcesMap: null,
                sources: [{
                        dataCid: 'data1',
                        pieceCid: 'piece1',
                        selector: []
                    }, {
                        dataCid: 'data2',
                        pieceCid: 'piece2',
                        selector: []
                    }]
            };
            expect(result.value).toEqual(expectedResult);
            const resultA = await service['ipfsClient'].dag.get(expectedCidA);
            const resultD = await service['ipfsClient'].dag.get(expectedCidD);
            const expectedResultA = {
                name: 'a',
                type: 'dir',
                entries: {
                    'b.mp4': {
                        name: 'b.mp4',
                        size: 100,
                        type: 'file',
                        sourcesMap: null,
                        sources: [
                            {
                                to: 100,
                                from: 0,
                                dataCid: 'data1',
                                pieceCid: 'piece1',
                                selector: [0, 0]
                            }
                        ]
                    },
                    'c.mp4': {
                        name: 'c.mp4',
                        size: 100,
                        type: 'file',
                        sourcesMap: null,
                        sources: [{
                                to: 50,
                                from: 0,
                                dataCid: 'data1',
                                pieceCid: 'piece1',
                                selector: [0, 1]
                            },
                            {
                                to: 100,
                                from: 50,
                                dataCid: 'data2',
                                pieceCid: 'piece2',
                                selector: [0, 0]
                            }]
                    }
                },
                sourcesMap: null,
                sources: [{
                        dataCid: 'data1',
                        pieceCid: 'piece1',
                        selector: [0]
                    }, {
                        dataCid: 'data2',
                        pieceCid: 'piece2',
                        selector: [0]
                    }]
            };
            const expectedResultD = {
                name: 'd',
                type: 'dir',
                entries: {
                    'e.mp4': {
                        name: 'e.mp4',
                        size: 100,
                        type: 'file',
                        sourcesMap: null,
                        sources: [{
                                to: 100,
                                from: 0,
                                dataCid: 'data2',
                                pieceCid: 'piece2',
                                selector: [1, 0]
                            }]
                    }
                },
                sourcesMap: null,
                sources: [{
                        dataCid: 'data2',
                        pieceCid: 'piece2',
                        selector: [1]
                    }]
            };
            expect(resultA.value).toEqual(expectedResultA);
            expect(resultD.value).toEqual(expectedResultD);
        });
    });
});
//# sourceMappingURL=IndexService.spec.js.map