/**
 * @file presetDataService.js
 * @author Radim Buráň (xburan03@stud.fit.vutbr.cz)
 */

const {prisma} = require("./dbService");

async function getByID(id) {
    return prisma.presetData.findUnique({
        where: {
            id: id
        },
        include: {
            devicePreset: true,
            publicPreset: true
        }
    }).then((r) => {
        return r
    }).catch((e) => {
        return {error: e}
    })
}

async function update(data) {
    return prisma.presetData.update({
        where: {
            id: data.id,
        },
        data: data
    }).then((r) => {
        return r;
    }).catch((e) => {
        return {error: e.message}
    });
}

async function getByFilter(filter, include = {}, max, page) {
    const whereFilter = {};
    if (filter.hasOwnProperty("id") && filter.id !== undefined) {
        whereFilter.id = filter.id;
    }
    if (filter.hasOwnProperty("humidity") && filter.humidity !== undefined) {
        whereFilter.humidity = filter.humidity;
    }
    if (filter.hasOwnProperty("humidityHysteresis") && filter.humidityHysteresis !== undefined) {
        whereFilter.humidityHysteresis = filter.humidityHysteresis;
    }

    const count = await prisma.presetData.count({
        where: whereFilter
    });

    return prisma.presetData.findMany({
        where: whereFilter,
        take: max,
        skip: max * page,
        include: {
            devicePreset: true,
            publicPreset: true
        }
    }).then((r) => {
        return {
            count: count,
            items: r
        };
    }).catch((e) => {
        return {error: e.message}
    });
}

module.exports = {
    getByID,
    update,
    getByFilter
}