1# -*- coding: utf-8 -*-
2from time import sleep
3
4from .baseapi import BaseAPI
5
6
7class Action(BaseAPI):
8    def __init__(self, *args, **kwargs):
9        self.id = None
10        self.status = None
11        self.type = None
12        self.started_at = None
13        self.completed_at = None
14        self.resource_id = None
15        self.resource_type = None
16        self.region = None
17        self.region_slug = None
18        # Custom, not provided by the json object.
19        self.droplet_id = None
20
21        super(Action, self).__init__(*args, **kwargs)
22
23    @classmethod
24    def get_object(cls, api_token, action_id):
25        """
26            Class method that will return a Action object by ID.
27        """
28        action = cls(token=api_token, id=action_id)
29        action.load_directly()
30        return action
31
32    def load_directly(self):
33        action = self.get_data("actions/%s" % self.id)
34        if action:
35            action = action[u'action']
36            # Loading attributes
37            for attr in action.keys():
38                setattr(self, attr, action[attr])
39
40    def load(self):
41        if not self.droplet_id:
42            action = self.load_directly()
43        else:
44            action = self.get_data(
45                "droplets/%s/actions/%s" % (
46                    self.droplet_id,
47                    self.id
48                )
49            )
50        if action:
51            action = action[u'action']
52            # Loading attributes
53            for attr in action.keys():
54                setattr(self, attr, action[attr])
55
56    def wait(self, update_every_seconds=1):
57        """
58            Wait until the action is marked as completed or with an error.
59            It will return True in case of success, otherwise False.
60
61            Optional Args:
62                update_every_seconds - int : number of seconds to wait before
63                    checking if the action is completed.
64        """
65        while self.status == u'in-progress':
66            sleep(update_every_seconds)
67            self.load()
68
69        return self.status == u'completed'
70
71    def __str__(self):
72        return "<Action: %s %s %s>" % (self.id, self.type, self.status)
73