summaryrefslogtreecommitdiff
path: root/server/button.py
blob: 1e79629f27b84ba6a786cd3258a635269fb067d4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import cherrypy
import sqlite3
import json
from lib import uuid
from lib import database
from time import time

STATUS_INVENTORY = 0
STATUS_ACTIVE = 1
STATUS_INACTIVE = 2
STATUS_SUSPENDED = 3
STATUS_DEAD = 4

def loadAll():
    db = database.connect()
    db.execute("SELECT id,status,last_pressed FROM buttons")

    results = []
    while True:
        try:
            button = Button()
            button.loadFromDb(db.fetchone())
            results.append(button.toDict())
        except:
            break

    return results

class Button(object):
    def __init__(self):
        self.persisted = False
        self.id = None
        self.status = STATUS_INVENTORY
        self.last_pressed = 0
        self.history = []

    def toDict(self):
        return {
            'id': self.id,
            'status': self.status,
            'last_pressed': self.last_pressed
        }

    def toJSON(self):
        return self.toDict()

    def loadById(self, id):
        db = database.connect()
        db.execute("SELECT id,status,last_pressed FROM buttons WHERE id = ?" , (str(id),))

        return self.loadFromDb(db.fetchone())

    def loadFromDb(self, dbrs):
        if dbrs is None:
            raise cherrypy.HTTPError(404, 'Button not found')

        self.persisted = True
        self.id, self.status, self.last_pressed = dbrs

        return self

    def press(self):
        if self.last_pressed:
            self.history.insert(0, self.last_pressed)

        self.last_pressed = int(time()) 
        return self

    def save(self):
        db = database.connect()

        # validate
        if self.id is None:
            raise cherrypy.HTTPError(500, "What u doin?")

        # upsert: update
        elif self.persisted:
            db.execute("UPDATE buttons SET status = ?, last_pressed = ? WHERE id = ?",
                (self.status, self.last_pressed, self.id,)
            )

        # upsert: insert
        else:
            db.execute("INSERT INTO buttons VALUES (?, ?, ?)", (self.id, self.status, self.last_pressed))

        db.connection.commit()
        return self

    def delete(self):
        db = database.connect()

        if self.id is None:
            raise cherrypy.HTTPError(500, "uhh wat")

        db.execute("DELETE FROM buttons WHERE id = ?", (self.id,))
        db.connection.commit()

        return None