1#
2# libraryBookDemo.py
3#
4# Simple statemachine demo, based on the state transitions given in librarybookstate.pystate
5#
6
7import statemachine
8import librarybookstate
9
10
11class Book(librarybookstate.BookStateMixin):
12    def __init__(self):
13        self.initialize_state(librarybookstate.New)
14
15
16class RestrictedBook(Book):
17    def __init__(self):
18        super(RestrictedBook, self).__init__()
19        self._authorized_users = []
20
21    def authorize(self, name):
22        self._authorized_users.append(name)
23
24    # specialized checkout to check permission of user first
25    def checkout(self, user=None):
26        if user in self._authorized_users:
27            super().checkout()
28        else:
29            raise Exception("{0} could not check out restricted book".format(user if user is not None else "anonymous"))
30
31
32def run_demo():
33    book = Book()
34    book.shelve()
35    print(book)
36    book.checkout()
37    print(book)
38    book.checkin()
39    print(book)
40    book.reserve()
41    print(book)
42    try:
43        book.checkout()
44    except Exception as e: # statemachine.InvalidTransitionException:
45        print(e)
46        print('..cannot check out reserved book')
47    book.release()
48    print(book)
49    book.checkout()
50    print(book)
51    print()
52
53    restricted_book = RestrictedBook()
54    restricted_book.authorize("BOB")
55    restricted_book.restrict()
56    print(restricted_book)
57    for name in [None, "BILL", "BOB"]:
58        try:
59            restricted_book.checkout(name)
60        except Exception as e:
61            print('..' + str(e))
62        else:
63            print('checkout to', name)
64    print(restricted_book)
65    restricted_book.checkin()
66    print(restricted_book)
67
68
69if __name__ == '__main__':
70    run_demo()
71