const db = require("../config/db");

class EntrancesService {
    getEntrances(house_id) {
        return new Promise((res, rej) => {
            let sql = `
                SELECT 
                    entrance.*, 
                    (SELECT house.title FROM house WHERE house.id = entrance.house_id) AS address_title,
                    (SELECT house.number FROM house WHERE house.id = entrance.house_id) AS address_number,
                    COALESCE((SELECT entrance_history.working FROM entrance_history WHERE entrance_history.entrance_id = entrance.id ORDER BY entrance_history.date_start DESC LIMIT 1), 0) AS working,
                    (SELECT entrance_history.name FROM entrance_history WHERE entrance_history.entrance_id = entrance.id ORDER BY entrance_history.date_start DESC LIMIT 1) AS entrance_history_name,
                    (SELECT entrance_history.group_id FROM entrance_history WHERE entrance_history.entrance_id = entrance.id ORDER BY entrance_history.date_start DESC LIMIT 1) AS entrance_history_group_id,
                    (SELECT entrance_history.sheep_id FROM entrance_history WHERE entrance_history.entrance_id = entrance.id ORDER BY entrance_history.date_start DESC LIMIT 1) AS entrance_history_sheep_id,
                    (SELECT entrance_history.id FROM entrance_history WHERE entrance_history.entrance_id = entrance.id ORDER BY entrance_history.date_start DESC LIMIT 1) AS entrance_history_id,
                    (SELECT entrance_history.date_start FROM entrance_history WHERE entrance_history.entrance_id = entrance.id ORDER BY entrance_history.date_start DESC LIMIT 1) AS entrance_history_date_start,
                    (SELECT entrance_history.date_end FROM entrance_history WHERE entrance_history.entrance_id = entrance.id ORDER BY entrance_history.date_start DESC LIMIT 1) AS entrance_history_date_end
                FROM 
                    entrance
                WHERE 
                    entrance.house_id = '${house_id}'
            `;

            db.all(sql, (err, rows) => {
                if (err) {
                    console.error(err.message);
                    return res(false);
                } else {
                    let data = rows.map((row) => {
                        return {
                            "id": Number(row.id),
                            "house_id": Number(row.house_id),
                            "entrance_number": Number(row.entrance_number),
                            "title": row.title,
                            "address": {
                                "title": row.address_title,
                                "number": row.address_number,
                                "points_number": JSON.parse(row.points_number)
                            },
                            "description": row.description,
                            "created_at": Number(row.created_at),
                            "updated_at": Number(row.updated_at),
                            "working": Number(row.working) == 0 ? false : true,
                            "history": {
                                "id": row.entrance_history_id ? Number(row.entrance_history_id) : null,
                                "name": row.entrance_history_name,
                                "group_id":  row.entrance_history_group_id ? Number(row.entrance_history_group_id) : null,
                                "sheep_id": row.entrance_history_sheep_id ? Number(row.entrance_history_sheep_id) : null,
                                "date": {
                                    "start": row.entrance_history_date_start ? Number(row.entrance_history_date_start) : null,
                                    "end": row.entrance_history_date_end ? Number(row.entrance_history_date_end) : null
                                }
                            }
                        }
                    })

                    return res(data);
                }
            });
        });
    }

    createEntrance(house_id, data) {
        return new Promise((res, rej) => {
            let sql = `
                INSERT INTO 
                    entrance(
                        house_id, 
                        entrance_number, 
                        title, 
                        description,
                        created_at
                    ) 
                VALUES 
                    (?, ?, ?, ?, ?)
            `;
            
            db.run(sql, [
                Number(house_id),
                Number(data.entrance_number),
                data.title,
                data.description,
                Math.floor(new Date(Date.now()).getTime())
            ], function(err) {
                if (err) {
                    console.error(err.message);
                    return res(false);
                } else if (this.changes === 0) {
                    return res(false);
                } else {
                    res({ "status": "ok", "id": this.lastID });
                }
            });
        });
    }

    updateEntrance(data) {
        return new Promise((res, rej) => {
            let sql = `
                UPDATE 
                    entrance
                SET 
                    title = ?,
                    description = ?,
                    updated_at = ?
                WHERE 
                    id = ?
            `;
            db.run(sql, [
                data.title,
                data.description,
                Math.floor(new Date(Date.now()).getTime()),
                data.id
            ], function(err) {
                if (err) {
                    console.error(err.message);
                    return res(false);
                } else if (this.changes === 0) {
                    return res(false);
                } else {
                    res({ "status": "ok", "id": data.id });
                }
            });
        });
    }

    deleteEntrance(data) {
        return new Promise((res, rej) => {
            db.run('DELETE FROM entrance WHERE id = ?', [data.id], function(err) {
                if (err) {
                    console.error(err.message);
                    return res(false);
                } else if (this.changes === 0) {
                    return res(false);
                } else {
                    res({ "status": "ok", "id": data.id });
                }
            });
        });
    }
}

module.exports = new EntrancesService();