"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.OcrRepository = void 0;
const common_1 = require("@nestjs/common");
const kysely_1 = require("kysely");
const nestjs_kysely_1 = require("nestjs-kysely");
const decorators_1 = require("../decorators");
let OcrRepository = class OcrRepository {
    db;
    constructor(db) {
        this.db = db;
    }
    getById(id) {
        return this.db.selectFrom('asset_ocr').selectAll('asset_ocr').where('asset_ocr.id', '=', id).executeTakeFirst();
    }
    getByAssetId(id, options) {
        const isVisible = options === undefined ? true : options.isVisible;
        return this.db
            .selectFrom('asset_ocr')
            .selectAll('asset_ocr')
            .where('asset_ocr.assetId', '=', id)
            .$if(isVisible !== undefined, (qb) => qb.where('asset_ocr.isVisible', '=', isVisible))
            .execute();
    }
    deleteAll() {
        return this.db.transaction().execute(async (trx) => {
            await (0, kysely_1.sql) `truncate ${kysely_1.sql.table('asset_ocr')}`.execute(trx);
            await (0, kysely_1.sql) `truncate ${kysely_1.sql.table('ocr_search')}`.execute(trx);
        });
    }
    upsert(assetId, ocrDataList, searchText) {
        let query = this.db.with('deleted_ocr', (db) => db.deleteFrom('asset_ocr').where('assetId', '=', assetId));
        if (ocrDataList.length > 0) {
            query = query
                .with('inserted_ocr', (db) => db.insertInto('asset_ocr').values(ocrDataList))
                .with('inserted_search', (db) => db
                .insertInto('ocr_search')
                .values({ assetId, text: searchText })
                .onConflict((oc) => oc.column('assetId').doUpdateSet((eb) => ({ text: eb.ref('excluded.text') }))));
        }
        else {
            query = query.with('deleted_search', (db) => db.deleteFrom('ocr_search').where('assetId', '=', assetId));
        }
        return query.selectNoFrom((0, kysely_1.sql) `1`.as('dummy')).execute();
    }
    async updateOcrVisibilities(assetId, visible, hidden) {
        await this.db.transaction().execute(async (trx) => {
            if (visible.length > 0) {
                await trx
                    .updateTable('asset_ocr')
                    .set({ isVisible: true })
                    .where('asset_ocr.id', 'in', visible.map((i) => i.id))
                    .execute();
            }
            if (hidden.length > 0) {
                await trx
                    .updateTable('asset_ocr')
                    .set({ isVisible: false })
                    .where('asset_ocr.id', 'in', hidden.map((i) => i.id))
                    .execute();
            }
            const searchText = visible.map((item) => item.text.trim()).join(' ');
            await trx.updateTable('ocr_search').set({ text: searchText }).where('assetId', '=', assetId).execute();
        });
    }
};
exports.OcrRepository = OcrRepository;
__decorate([
    (0, decorators_1.GenerateSql)({ params: [decorators_1.DummyValue.UUID] }),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String]),
    __metadata("design:returntype", void 0)
], OcrRepository.prototype, "getById", null);
__decorate([
    (0, decorators_1.GenerateSql)({ params: [decorators_1.DummyValue.UUID] }),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, Object]),
    __metadata("design:returntype", void 0)
], OcrRepository.prototype, "getByAssetId", null);
__decorate([
    (0, decorators_1.GenerateSql)({
        params: [
            decorators_1.DummyValue.UUID,
            [
                {
                    assetId: decorators_1.DummyValue.UUID,
                    x1: decorators_1.DummyValue.NUMBER,
                    y1: decorators_1.DummyValue.NUMBER,
                    x2: decorators_1.DummyValue.NUMBER,
                    y2: decorators_1.DummyValue.NUMBER,
                    x3: decorators_1.DummyValue.NUMBER,
                    y3: decorators_1.DummyValue.NUMBER,
                    x4: decorators_1.DummyValue.NUMBER,
                    y4: decorators_1.DummyValue.NUMBER,
                    text: decorators_1.DummyValue.STRING,
                    boxScore: decorators_1.DummyValue.NUMBER,
                    textScore: decorators_1.DummyValue.NUMBER,
                },
            ],
            decorators_1.DummyValue.STRING,
        ],
    }),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, Array, String]),
    __metadata("design:returntype", void 0)
], OcrRepository.prototype, "upsert", null);
__decorate([
    (0, decorators_1.GenerateSql)({ params: [decorators_1.DummyValue.UUID, [], []] }),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, Array, Array]),
    __metadata("design:returntype", Promise)
], OcrRepository.prototype, "updateOcrVisibilities", null);
exports.OcrRepository = OcrRepository = __decorate([
    (0, common_1.Injectable)(),
    __param(0, (0, nestjs_kysely_1.InjectKysely)()),
    __metadata("design:paramtypes", [kysely_1.Kysely])
], OcrRepository);
//# sourceMappingURL=ocr.repository.js.map