import {dbService} from './dbService.js';

class CookieService {
    createRoom(name) {
        return new Promise(function (resolve, reject) {
            const createRoom = 'INSERT INTO room (name, count) VALUES($1,$2) RETURNING id';
            const createRoomValues = [name, 0];
            dbService.client.query(createRoom, createRoomValues)
                .then(res => {
                    resolve(res.rows[0].id);
                })
                .catch(err => {
                    console.log(err.stack);
                    resolve(false);
                });
        });
    }

    joinRoom(user, roomId) {
        return new Promise(function (resolve, reject) {
            const createRoomAssignment = 'INSERT INTO roomassignment (userid, roomid) VALUES($1,$2)';
            const createRoomAssignmentValues = [user, roomId];
            dbService.client.query(createRoomAssignment, createRoomAssignmentValues)
                .then(res => {
                    resolve(true);
                })
                .catch(err => {
                    console.log(err.stack);
                    resolve(false);
                });
        });
    }

    getRooms(user) {
        return new Promise(function(resolve, reject) {
           const getRoomsQuery = 'SELECT * FROM room r JOIN roomassignment ra ON r.id = ra.roomid WHERE userid = $1';
           const getRoomsQueryValues = [user.id];
           dbService.client.query(getRoomsQuery, getRoomsQueryValues)
               .then(res => {
                   res.rows.sort((a,b) =>
                       a.count > b.count ? -1 : 1
                   );
                   resolve(res.rows);
               })
               .catch(err => {
                   console.log(err.stack);
                   resolve(false);
               });
        });
    }

    getRoomById(roomId) {
        return new Promise(function(resolve, reject) {
            const getRoomQuery = 'SELECT * FROM room WHERE id = $1';
            const getRoomQueryValues = [roomId];
            dbService.client.query(getRoomQuery, getRoomQueryValues)
                .then(res => {
                    resolve(res.rows);
                })
                .catch(err => {
                    console.log(err.stack);
                    resolve(false);
                });
        });
    }

    incrementCookieClicks(roomId) {
       const incrementCookieClicksQuery = 'UPDATE room SET count = count + 1 where id = $1';
       const incrementCookieClicksQueryValues = [roomId];
       dbService.client.query(incrementCookieClicksQuery, incrementCookieClicksQueryValues);
    }



}
export const cookieService = new CookieService();
