"use strict";
/*
 * server component for the TimeLimit App
 * Copyright (C) 2019 - 2022 Jonas Lochmann
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, version 3 of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.dispatchUpdateCategoryBlockedTimes = dispatchUpdateCategoryBlockedTimes;
const updatecategoryblockedtimes_1 = require("../../../../action/updatecategoryblockedtimes");
const bitmask_1 = require("../../../../util/bitmask");
const missing_item_1 = require("../exception/missing-item");
const self_limit_1 = require("../exception/self-limit");
async function dispatchUpdateCategoryBlockedTimes({ action, cache, fromChildSelfLimitAddChildUserId }) {
    const categoryEntryUnsafe = await cache.database.category.findOne({
        where: {
            familyId: cache.familyId,
            categoryId: action.categoryId
        },
        transaction: cache.transaction,
        attributes: ['childId', 'blockedMinutesInWeek']
    });
    if (!categoryEntryUnsafe) {
        throw new missing_item_1.MissingCategoryException();
    }
    const categoryEntry = {
        childId: categoryEntryUnsafe.childId,
        blockedMinutesInWeek: categoryEntryUnsafe.blockedMinutesInWeek
    };
    if (fromChildSelfLimitAddChildUserId !== null) {
        if (categoryEntry.childId !== fromChildSelfLimitAddChildUserId) {
            throw new self_limit_1.CanNotModifyOtherUsersBySelfLimitationException();
        }
        const oldBlocked = (0, bitmask_1.validateAndParseBitmask)(categoryEntry.blockedMinutesInWeek, updatecategoryblockedtimes_1.blockedTimesBitmaskLength);
        const newBlocked = (0, bitmask_1.validateAndParseBitmask)(action.blockedTimes, updatecategoryblockedtimes_1.blockedTimesBitmaskLength);
        oldBlocked.forEach((value, index) => {
            if (value && !newBlocked[index]) {
                throw new self_limit_1.SelfLimitationException({ staticMessage: 'new blocked time areas are smaller' });
            }
        });
    }
    await cache.database.category.update({
        blockedMinutesInWeek: action.blockedTimes
    }, {
        where: {
            familyId: cache.familyId,
            categoryId: action.categoryId
        },
        transaction: cache.transaction
    });
    cache.categoriesWithModifiedBaseData.add(action.categoryId);
    cache.incrementTriggeredSyncLevel(2);
}
//# sourceMappingURL=updatecategoryblockedtimes.js.map