"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.BoardResolver = void 0;
const type_graphql_1 = require("type-graphql");
const typeorm_1 = require("typeorm");
const uuid_1 = require("uuid");
const board_service_1 = require("@things-factory/board-service");
const operato_license_checker_1 = require("@things-factory/operato-license-checker");
const license_error_1 = require("../../errors/license-error");
const domain_secret_1 = require("../domain-secret/domain-secret");
const board_secret_1 = require("./board-secret");
const debug = require('debug')('things-factory:operato-board:board-resolver');
let BoardResolver = class BoardResolver {
    boardPermissions(context) {
        return ((0, operato_license_checker_1.getPermission)('Permissions For Board Usage') || 'Modeller, Viewer').split(',').map(p => p.trim());
    }
    async board(id, context) {
        const { domain } = context.state;
        var board = await (0, typeorm_1.getRepository)(board_service_1.Board).findOne({
            where: { domain, id }
        });
        if (domain) {
            // 1. check domainSecret is over limit quantity or not
            var count = (await (0, typeorm_1.getRepository)(domain_secret_1.DomainSecret)
                .manager.createQueryBuilder()
                .select('board')
                .from(domain_secret_1.DomainSecret, 'secret')
                .where('id = :domainId', { domainId: domain.id })
                .getCount()) + 1;
            if (!(0, operato_license_checker_1.checkTarget)(count)) {
                throw new license_error_1.LicenseError({
                    errorCode: context.t(license_error_1.LicenseError.ERROR_CODES.OVER_LIMIT)
                });
            }
            else {
                var domainSecret = await (0, typeorm_1.getRepository)(domain_secret_1.DomainSecret).findOne({
                    where: { domain: domain }
                });
                // 2. if there's no domainSecret then create it
                if (!domainSecret) {
                    var domainSecret = new domain_secret_1.DomainSecret();
                    domainSecret.id = (0, uuid_1.v4)();
                    domainSecret.domain = domain;
                    var hash = (0, operato_license_checker_1.doSomething)({ secId: domainSecret.id, id: domain.id });
                    domainSecret.secret = hash;
                    await (0, typeorm_1.getRepository)(domain_secret_1.DomainSecret).save(domainSecret);
                    // 3. if there's domainSecret then check it
                }
                else {
                    var domainRepo = (0, typeorm_1.getRepository)(domain_secret_1.DomainSecret);
                    var domainSecret = await domainRepo.findOne({
                        where: { domain: domain }
                    });
                    if (domainSecret) {
                        var hash = (0, operato_license_checker_1.doSomething)({ secId: domainSecret.id, id: domain.id });
                        if (domainSecret.secret !== hash) {
                            throw new license_error_1.LicenseError({
                                errorCode: context.t(license_error_1.LicenseError.ERROR_CODES.VERIFICATION_ERROR)
                            });
                        }
                    }
                    else {
                        throw new license_error_1.LicenseError({
                            errorCode: context.t(license_error_1.LicenseError.ERROR_CODES.VERIFICATION_ERROR)
                        });
                    }
                }
            }
        }
        if (board) {
            // 1. check boardSecret is over limit quantity or not
            var count = (await (0, typeorm_1.getRepository)(board_secret_1.BoardSecret)
                .manager.createQueryBuilder()
                .select('board')
                .from(board_secret_1.BoardSecret, 'secret')
                .where('domain_id = :domainId', { domainId: domain.id })
                .getCount()) + 1;
            if (!(0, operato_license_checker_1.checkTarget)(count)) {
                throw new license_error_1.LicenseError({
                    errorCode: context.t(license_error_1.LicenseError.ERROR_CODES.OVER_LIMIT)
                });
            }
            else {
                var boardSecret = await (0, typeorm_1.getRepository)(board_secret_1.BoardSecret).findOne({
                    where: { targetId: id }
                });
                // 2. if there's no boardSecret then create it
                if (!boardSecret) {
                    var boardSecret = new board_secret_1.BoardSecret();
                    boardSecret.id = (0, uuid_1.v4)();
                    boardSecret.targetId = id;
                    boardSecret.targetType = 'board';
                    boardSecret.domain = domain;
                    var hash = (0, operato_license_checker_1.doSomething)({ secId: boardSecret.id, id: id });
                    boardSecret.secret = hash;
                    await (0, typeorm_1.getRepository)(board_secret_1.BoardSecret).save(boardSecret);
                    // 3. if there's boardSecret then check it
                }
                else {
                    var repogitory = (0, typeorm_1.getRepository)(board_secret_1.BoardSecret);
                    var boardSecret = await repogitory.findOne({
                        where: { targetId: id }
                    });
                    if (boardSecret) {
                        var hash = (0, operato_license_checker_1.doSomething)({ secId: boardSecret.id, id: id });
                        if (boardSecret.secret !== hash) {
                            throw new license_error_1.LicenseError({
                                errorCode: context.t(license_error_1.LicenseError.ERROR_CODES.VERIFICATION_ERROR)
                            });
                        }
                    }
                    else {
                        throw new license_error_1.LicenseError({
                            errorCode: context.t(license_error_1.LicenseError.ERROR_CODES.VERIFICATION_ERROR)
                        });
                    }
                }
            }
        }
        return board;
    }
};
__decorate([
    (0, type_graphql_1.Query)(returns => [String], { description: 'Board Usage Permissions' }),
    __param(0, (0, type_graphql_1.Ctx)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Array)
], BoardResolver.prototype, "boardPermissions", null);
__decorate([
    (0, type_graphql_1.Query)(returns => board_service_1.Board, { description: 'To fetch a board' }),
    __param(0, (0, type_graphql_1.Arg)('id')),
    __param(1, (0, type_graphql_1.Ctx)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, Object]),
    __metadata("design:returntype", Promise)
], BoardResolver.prototype, "board", null);
BoardResolver = __decorate([
    (0, type_graphql_1.Resolver)(board_service_1.Board)
], BoardResolver);
exports.BoardResolver = BoardResolver;
//# sourceMappingURL=board-resolver.js.map