1# Copyright (c) 2006,2007 Mitch Garnaat http://garnaat.org/
2#
3# Permission is hereby granted, free of charge, to any person obtaining a
4# copy of this software and associated documentation files (the
5# "Software"), to deal in the Software without restriction, including
6# without limitation the rights to use, copy, modify, merge, publish, dis-
7# tribute, sublicense, and/or sell copies of the Software, and to permit
8# persons to whom the Software is furnished to do so, subject to the fol-
9# lowing conditions:
10#
11# The above copyright notice and this permission notice shall be included
12# in all copies or substantial portions of the Software.
13#
14# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
16# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
17# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
18# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
20# IN THE SOFTWARE.
21import os
22
23def int_val_fn(v):
24    try:
25        int(v)
26        return True
27    except:
28        return False
29
30class IObject(object):
31
32    def choose_from_list(self, item_list, search_str='',
33                         prompt='Enter Selection'):
34        if not item_list:
35            print('No Choices Available')
36            return
37        choice = None
38        while not choice:
39            n = 1
40            choices = []
41            for item in item_list:
42                if isinstance(item, basestring):
43                    print('[%d] %s' % (n, item))
44                    choices.append(item)
45                    n += 1
46                else:
47                    obj, id, desc = item
48                    if desc:
49                        if desc.find(search_str) >= 0:
50                            print('[%d] %s - %s' % (n, id, desc))
51                            choices.append(obj)
52                            n += 1
53                    else:
54                        if id.find(search_str) >= 0:
55                            print('[%d] %s' % (n, id))
56                            choices.append(obj)
57                            n += 1
58            if choices:
59                val = raw_input('%s[1-%d]: ' % (prompt, len(choices)))
60                if val.startswith('/'):
61                    search_str = val[1:]
62                else:
63                    try:
64                        int_val = int(val)
65                        if int_val == 0:
66                            return None
67                        choice = choices[int_val-1]
68                    except ValueError:
69                        print('%s is not a valid choice' % val)
70                    except IndexError:
71                        print('%s is not within the range[1-%d]' % (val,
72                                                                    len(choices)))
73            else:
74                print("No objects matched your pattern")
75                search_str = ''
76        return choice
77
78    def get_string(self, prompt, validation_fn=None):
79        okay = False
80        while not okay:
81            val = raw_input('%s: ' % prompt)
82            if validation_fn:
83                okay = validation_fn(val)
84                if not okay:
85                    print('Invalid value: %s' % val)
86            else:
87                okay = True
88        return val
89
90    def get_filename(self, prompt):
91        okay = False
92        val = ''
93        while not okay:
94            val = raw_input('%s: %s' % (prompt, val))
95            val = os.path.expanduser(val)
96            if os.path.isfile(val):
97                okay = True
98            elif os.path.isdir(val):
99                path = val
100                val = self.choose_from_list(os.listdir(path))
101                if val:
102                    val = os.path.join(path, val)
103                    okay = True
104                else:
105                    val = ''
106            else:
107                print('Invalid value: %s' % val)
108                val = ''
109        return val
110
111    def get_int(self, prompt):
112        s = self.get_string(prompt, int_val_fn)
113        return int(s)
114
115