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

class HomesteadsService {
    getList(mode, id) {
        return new Promise((res, rej) => {
            let sql = `
                SELECT 
                    homestead.*, 
                    COALESCE((SELECT homestead_history.working FROM homestead_history WHERE homestead_history.homestead_id = homestead.id ORDER BY homestead_history.date_start DESC LIMIT 1), 0) AS working,
                    (SELECT homestead_history.name FROM homestead_history WHERE homestead_history.homestead_id = homestead.id ORDER BY homestead_history.date_start DESC LIMIT 1) AS homestead_history_name,
                    (SELECT homestead_history.group_id FROM homestead_history WHERE homestead_history.homestead_id = homestead.id ORDER BY homestead_history.date_start DESC LIMIT 1) AS homestead_history_group_id,
                    (SELECT homestead_history.sheep_id FROM homestead_history WHERE homestead_history.homestead_id = homestead.id ORDER BY homestead_history.date_start DESC LIMIT 1) AS homestead_history_sheep_id,
                    (SELECT homestead_history.id FROM homestead_history WHERE homestead_history.homestead_id = homestead.id ORDER BY homestead_history.date_start DESC LIMIT 1) AS homestead_history_id,
                    (SELECT homestead_history.date_start FROM homestead_history WHERE homestead_history.homestead_id = homestead.id ORDER BY homestead_history.date_start DESC LIMIT 1) AS homestead_history_date_start,
                    (SELECT homestead_history.date_end FROM homestead_history WHERE homestead_history.homestead_id = homestead.id ORDER BY homestead_history.date_start DESC LIMIT 1) AS homestead_history_date_end
                FROM 
                    homestead
            `;

            if (mode == "group") {
                sql = `
                    SELECT 
                        homestead.*, 
                        COALESCE((SELECT homestead_history.working FROM homestead_history WHERE homestead_history.homestead_id = homestead.id ORDER BY homestead_history.date_start DESC LIMIT 1), 0) AS working,
                        (SELECT homestead_history.name FROM homestead_history WHERE homestead_history.homestead_id = homestead.id ORDER BY homestead_history.date_start DESC LIMIT 1) AS homestead_history_name,
                        (SELECT homestead_history.group_id FROM homestead_history WHERE homestead_history.homestead_id = homestead.id ORDER BY homestead_history.date_start DESC LIMIT 1) AS homestead_history_group_id,
                        (SELECT homestead_history.sheep_id FROM homestead_history WHERE homestead_history.homestead_id = homestead.id ORDER BY homestead_history.date_start DESC LIMIT 1) AS homestead_history_sheep_id,
                        (SELECT homestead_history.id FROM homestead_history WHERE homestead_history.homestead_id = homestead.id ORDER BY homestead_history.date_start DESC LIMIT 1) AS homestead_history_id,
                        (SELECT homestead_history.date_start FROM homestead_history WHERE homestead_history.homestead_id = homestead.id ORDER BY homestead_history.date_start DESC LIMIT 1) AS homestead_history_date_start,
                        (SELECT homestead_history.date_end FROM homestead_history WHERE homestead_history.homestead_id = homestead.id ORDER BY homestead_history.date_start DESC LIMIT 1) AS homestead_history_date_end
                    FROM 
                        homestead
                    JOIN 
                        homestead_history
                    ON 
                        homestead.id = homestead_history.homestead_id
                    AND
                        homestead_history.working = 1
                    AND 
                        homestead_history.name = 'Групова'
                    AND 
                        homestead_history.group_id = '${id}'
                `;
            } else if (mode == "sheep" || mode == "admin") {
                sql = `
                    SELECT 
                        homestead.*,
                        homestead_history.homestead_id,
                        homestead_history.name AS homestead_history_name,
                        homestead_history.group_id AS homestead_history_group_id,
                        homestead_history.sheep_id AS homestead_history_sheep_id,
                        homestead_history.id AS homestead_history_id,
                        homestead_history.date_start AS homestead_history_date_start,
                        homestead_history.date_end AS homestead_history_date_end
                    FROM 
                        homestead
                    JOIN 
                        homestead_history
                    ON 
                        homestead.id = homestead_history.homestead_id
                    AND
                        homestead_history.working = 1 
                    AND 
                        homestead_history.sheep_id = '${id}';
                `;
            } else if (mode == "joint") {
                sql = `
                    SELECT 
                        homestead.*,
                        homestead_history.id AS homestead_history_id,
                        homestead_history.name AS homestead_history_name,
                        homestead_history.group_id AS homestead_history_group_id,
                        homestead_history.sheep_id AS homestead_history_sheep_id,
                        homestead_history.date_start AS homestead_history_date_start,
                        homestead_history.date_end AS homestead_history_date_end
                    FROM 
                        homestead
                    JOIN 
                        homestead_history ON homestead.id = homestead_history.homestead_id
                    JOIN 
                        homestead_joint ON homestead.id = homestead_joint.homestead_id
                    WHERE 
                        homestead_joint.sheep_id = '${id}'
                    ORDER BY 
                        homestead_history.date_start DESC;
                `;
            }

            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),
                            "title": row.title,
                            "number": row.number,
                            "points": JSON.parse(row.points),
                            "geo": JSON.parse(row.geo),
                            "zoom": Number(row.zoom),
                            "osm_id": JSON.parse(row.osm_id),
                            "settlement": row.settlement,
                            "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.homestead_history_id ? Number(row.homestead_history_id) : null,
                                "name": row.homestead_history_name,
                                "group_id": row.homestead_history_group_id ? Number(row.homestead_history_group_id) : null,
                                "sheep_id": row.homestead_history_sheep_id ? Number(row.homestead_history_sheep_id) : null,
                                "date": {
                                    "start": row.homestead_history_date_start ? Number(row.homestead_history_date_start) : null,
                                    "end": row.homestead_history_date_end ? Number(row.homestead_history_date_end) : null
                                }
                            }
                        }
                    })

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

    getHomestead(homestead_id) {
        return new Promise((res, rej) => {
            let sql = `
                SELECT 
                    homestead.*,
                    COALESCE((SELECT homestead_history.working FROM homestead_history WHERE homestead_history.homestead_id = homestead.id ORDER BY homestead_history.date_start DESC LIMIT 1), 0) AS working,
                    (SELECT homestead_history.name FROM homestead_history WHERE homestead_history.homestead_id = homestead.id ORDER BY homestead_history.date_start DESC LIMIT 1) AS homestead_history_name,
                    (SELECT homestead_history.group_id FROM homestead_history WHERE homestead_history.homestead_id = homestead.id ORDER BY homestead_history.date_start DESC LIMIT 1) AS homestead_history_group_id,
                    (SELECT homestead_history.sheep_id FROM homestead_history WHERE homestead_history.homestead_id = homestead.id ORDER BY homestead_history.date_start DESC LIMIT 1) AS homestead_history_sheep_id,
                    (SELECT homestead_history.id FROM homestead_history WHERE homestead_history.homestead_id = homestead.id ORDER BY homestead_history.date_start DESC LIMIT 1) AS homestead_history_id,
                    (SELECT homestead_history.date_start FROM homestead_history WHERE homestead_history.homestead_id = homestead.id ORDER BY homestead_history.date_start DESC LIMIT 1) AS homestead_history_date_start,
                    (SELECT homestead_history.date_end FROM homestead_history WHERE homestead_history.homestead_id = homestead.id ORDER BY homestead_history.date_start DESC LIMIT 1) AS homestead_history_date_end
                FROM 
                    homestead
                WHERE 
                    homestead.id = '${homestead_id}'
            `;

            db.get(sql, (err, row) => {
                if (err) {
                    console.error(err.message);
                    return res(false);
                } else if (!row) {
                    console.log({ "error": "house not found" });
                    return res(false);
                } else {
                    let data = {
                        "id": Number(row.id),
                        "title": row.title,
                        "number": row.number,
                        "points": JSON.parse(row.points),
                        "geo": JSON.parse(row.geo),
                        "zoom": Number(row.zoom),
                        "osm_id": JSON.parse(row.osm_id),
                        "settlement": row.settlement,
                        "description": row.description,
                        "updated_at": Number(row.updated_at),
                        "working": Number(row.working) == 0 ? false : true,
                        "history": {
                            "id": row.homestead_history_id ? Number(row.homestead_history_id) : null,
                            "name": row.homestead_history_name,
                            "group_id": row.homestead_history_group_id ? Number(row.homestead_history_group_id) : null,
                            "sheep_id": row.homestead_history_sheep_id ? Number(row.homestead_history_sheep_id) : null,
                            "date": {
                                "start": row.homestead_history_date_start ? Number(row.homestead_history_date_start) : null,
                                "end": row.homestead_history_date_end ? Number(row.homestead_history_date_end) : null
                            }
                        }
                    }

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

    createHomestead(data) {
        return new Promise((res, rej) => {
            let sql = `
                INSERT INTO 
                    homestead(
                        title,
                        number,
                        points,
                        geo,
                        zoom,
                        osm_id,
                        settlement,
                        created_at
                    ) 
                VALUES 
                    (?, ?, ?, ?, ?, ?, ?, ?)
            `;

            db.run(sql, [
                data.title,
                data.number,
                JSON.stringify(data.points),
                JSON.stringify(data.geo),
                Number(data.zoom),
                JSON.stringify(data.osm_id),
                data.settlement,
                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 });
                    genCards({type: "homestead", id: this.lastID});
                }
            });
        });
    }

    updateHomestead(homestead_id, data) {
        return new Promise((res, rej) => {
            let sql = `
                UPDATE 
                    homestead
                SET 
                    title = ?,
                    number = ?,
                    points = ?,
                    geo = ?,
                    zoom = ?,
                    osm_id = ?,
                    settlement = ?,
                    description = ?,
                    updated_at = ?
                WHERE 
                    id = ?
            `;
            db.run(sql, [
                data.title,
                data.number,
                JSON.stringify(data.points),
                JSON.stringify(data.geo),
                Number(data.zoom),
                JSON.stringify(data.osm_id),
                data.settlement,
                data.description,
                Math.floor(new Date(Date.now()).getTime()),
                homestead_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": homestead_id });
                    genCards({type: "homestead", id: homestead_id});
                }
            });
        });
    }

    deleteHomestead(homestead_id) {
        return new Promise((res, rej) => {
            db.run('DELETE FROM homestead WHERE id = ?', [homestead_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": homestead_id });
                }
            });
        });
    }
}

module.exports = new HomesteadsService();