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

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

async function getByID(id, include  = {owner: false, preset: false}) {
    return prisma.device.findUnique({
        where: {
            id: id
        },
        include: include
    }).then((r) => {
        return r
    }).catch((e) => {
        return {error: e.message}
    })
}

async function createForUser(userID, data) {
    return prisma.device.create({
        data: {
            ...data,
            owner: {
                connect: {
                    id: userID
                }
            },
            preset: {       /* DevicePreset */
                create: {
                    data: { /* PresetData */
                        create: {

                        }
                    }
                }
            }
        }
    }).then(async (r) => {
        return r;
    }).catch((e) => {
        return {error: e.message}
    });
}

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

async function deleteByID(id) {
    return prisma.device.delete({
        where: {
            id: id
        }
    }).then((r) => {
        return r;
    }).catch((e) => {
        return {error: e}
    });
}

async function getByFilter(filter, include = {owner: false, preset: false}, max, page) {
    const whereFilter = {};
    if (filter.hasOwnProperty("id") && filter.id !== undefined) {
        whereFilter.id = filter.id;
    }
    if (filter.hasOwnProperty("ownerId") && filter.ownerId !== undefined) {
        whereFilter.ownerId = Number(filter.ownerId);
    }
    if (filter.hasOwnProperty("name") && filter.name !== undefined) {
        whereFilter.name = {
            contains: filter.name
        }
    }
    if (filter.hasOwnProperty("owner") && filter.owner !== undefined) {
        whereFilter.owner = {
            is: {
                name: {
                    contains: filter.owner
                }
            }
        };
    }

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

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

module.exports = {
    getByID,
    createForUser,
    update,
    deleteByID,
    getByFilter
}