Completed
Push — master ( c87d3f...a90c58 )
by Oleksandr
02:16
created

AirForces.get_flight_prefixes()   A

Complexity

Conditions 3

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 6
ccs 5
cts 5
cp 1
rs 9.4285
cc 3
crap 3
1
# -*- coding: utf-8 -*-
2
3 1
import os
4 1
import six
5
6 1
if six.PY2:
7
    from io import open
8
9 1
from candv import (
10
    Values, VerboseConstant, VerboseValueConstant, with_constant_class,
11
)
12 1
from verboselib import get_language
13
14 1
from . import SupportedLanguages
15 1
from .utils import translations
16
17
18 1
_ = translations.ugettext_lazy
19
20
21 1
class Belligerents(Values):
22 1
    none = VerboseValueConstant(0, _("neutral"))
23 1
    red = VerboseValueConstant(1, _("allies"))
24 1
    blue = VerboseValueConstant(2, _("axis"))
25 1
    green = VerboseValueConstant(3, _("green"))
26 1
    gold = VerboseValueConstant(4, _("gold"))
27 1
    purple = VerboseValueConstant(5, _("purple"))
28 1
    aqua = VerboseValueConstant(6, _("aqua"))
29 1
    maroon = VerboseValueConstant(7, _("maroon"))
30 1
    navy = VerboseValueConstant(8, _("navy"))
31 1
    emerald = VerboseValueConstant(9, _("emerald"))
32 1
    olive = VerboseValueConstant(10, _("olive"))
33 1
    magenta = VerboseValueConstant(11, _("magenta"))
34 1
    teal = VerboseValueConstant(12, _("teal"))
35 1
    orange = VerboseValueConstant(13, _("orange"))
36 1
    turquoise = VerboseValueConstant(14, _("turquoise"))
37 1
    brown = VerboseValueConstant(15, _("brown"))
38 1
    salad = VerboseValueConstant(16, _("salad"))
39
40
41 1
class Country(VerboseConstant):
42
43 1
    def __init__(self, belligerent, verbose_name=None, help_text=None):
44 1
        super(Country, self).__init__(verbose_name=verbose_name,
45
                                      help_text=help_text)
46 1
        self.belligerent = belligerent
47
48 1
    def merge_into_group(self, group):
49 1
        super(Country, self).merge_into_group(group)
50 1
        group.belligerent = self.belligerent
51
52 1
    def to_primitive(self, context=None):
53 1
        primitive = super(Country, self).to_primitive(context)
54 1
        primitive['belligerent'] = self.belligerent.to_primitive(context)
55 1
        return primitive
56
57
58 1
class Countries(with_constant_class(Country), Values):
59 1
    au = Country(Belligerents.red, _("Australia"))
60 1
    fi = Country(Belligerents.blue, _("Finland"))
61 1
    fr = Country(Belligerents.red, _("France"))
62 1
    de = Country(Belligerents.blue, _("Germany"))
63 1
    hu = Country(Belligerents.blue, _("Hungary"))
64 1
    jp = Country(Belligerents.blue, _("Japan"))
65 1
    it = Country(Belligerents.blue, _("Italy"))
66 1
    nl = Country(Belligerents.red, _("Netherlands"))
67 1
    nz = Country(Belligerents.red, _("New Zealand"))
68 1
    pl = Country(Belligerents.red, _("Poland"))
69 1
    ro = Country(Belligerents.blue, _("Romania"))
70 1
    sk = Country(Belligerents.blue, _("Slovakia"))
71 1
    su = Country(Belligerents.red, _("Soviet Union"))
72 1
    uk = Country(Belligerents.red, _("United Kingdom"))
73 1
    us = Country(Belligerents.red, _("United States"))
74
75 1
    @classmethod
76
    def filter_by_belligerent(cls, belligerent):
77 1
        return filter(lambda x: x.belligerent == belligerent, cls.constants())
78
79
80 1
class AirForce(VerboseValueConstant):
81
82 1
    def __init__(self, country, default_flight_prefix, value,
83
                 verbose_name=None, help_text=None):
84 1
        super(AirForce, self).__init__(value,
85
                                       verbose_name=verbose_name,
86
                                       help_text=help_text)
87 1
        self.country = country
88
89 1
        if default_flight_prefix is not None:
90 1
            self.default_flight_prefix = str(default_flight_prefix)
91
        else:
92 1
            self.default_flight_prefix = None
93
94 1
    def merge_into_group(self, group):
95 1
        super(AirForce, self).merge_into_group(group)
96 1
        group.country = self.country
97 1
        group.default_flight_prefix = self.default_flight_prefix
98
99 1
    def to_primitive(self, context=None):
100 1
        primitive = super(AirForce, self).to_primitive(context)
101 1
        country = self.country and self.country.to_primitive(context)
102 1
        primitive.update({
103
            'country': country,
104
            'default_flight_prefix': self.default_flight_prefix,
105
        })
106 1
        return primitive
107
108
109 1
class AirForces(with_constant_class(AirForce), Values):
110 1
    ala = AirForce(
111
        country=Countries.fr,
112
        default_flight_prefix='fr01',
113
        value='fr',
114
        verbose_name=_("ALA"),
115
        help_text=_("Army of the Air"),
116
    )
117 1
    faf = AirForce(
118
        country=Countries.fi,
119
        default_flight_prefix='f01',
120
        value='fi',
121
        verbose_name=_("FAF"),
122
        help_text=_("Finnish Air Force"),
123
    )
124 1
    far = AirForce(
125
        country=Countries.ro,
126
        default_flight_prefix='ro01',
127
        value='ro',
128
        verbose_name=_("FAR"),
129
        help_text=_("Romanian Air Force"),
130
    )
131 1
    haf = AirForce(
132
        country=Countries.hu,
133
        default_flight_prefix='h01',
134
        value='hu',
135
        verbose_name=_("HAF"),
136
        help_text=_("Hungarian Air Force"),
137
    )
138 1
    luftwaffe = AirForce(
139
        country=Countries.de,
140
        default_flight_prefix='g01',
141
        value='de',
142
        verbose_name=_("Luftwaffe"),
143
    )
144 1
    ija = AirForce(
145
        country=Countries.jp,
146
        default_flight_prefix='ja01',
147
        value='ja',
148
        verbose_name=_("IJA"),
149
        help_text=_("Imperial Japanese Army"),
150
    )
151 1
    ijn = AirForce(
152
        country=Countries.jp,
153
        default_flight_prefix='IN_NN',
154
        value='in',
155
        verbose_name=_("IJN"),
156
        help_text=_("Imperial Japanese Navy"),
157
    )
158 1
    paf = AirForce(
159
        country=Countries.pl,
160
        default_flight_prefix='pl01',
161
        value='pl',
162
        verbose_name=_("PAF"),
163
        help_text=_("Polish Air Force"),
164
    )
165 1
    rai = AirForce(
166
        country=Countries.it,
167
        default_flight_prefix='i01',
168
        value='it',
169
        verbose_name=_("RAI"),
170
        help_text=_("Regia Aeronautica Italiana"),
171
    )
172 1
    raaf = AirForce(
173
        country=Countries.au,
174
        default_flight_prefix='RA_NN',
175
        value='ra',
176
        verbose_name=_("RAAF"),
177
        help_text=_("Royal Australian Air Force"),
178
    )
179 1
    raf = AirForce(
180
        country=Countries.uk,
181
        default_flight_prefix='gb01',
182
        value='gb',
183
        verbose_name=_("RAF"),
184
        help_text=_("Royal Air Force"),
185
    )
186 1
    rn = AirForce(
187
        country=Countries.uk,
188
        default_flight_prefix='RN_NN',
189
        value='rn',
190
        verbose_name=_("RN"),
191
        help_text=_("Royal Navy"),
192
    )
193 1
    rnlaf = AirForce(
194
        country=Countries.nl,
195
        default_flight_prefix='DU_NN',
196
        value='du',
197
        verbose_name=_("RNLAF"),
198
        help_text=_("Royal Netherlands Air Force"),
199
    )
200 1
    rnzaf = AirForce(
201
        country=Countries.nz,
202
        default_flight_prefix='RZ_NN',
203
        value='rz',
204
        verbose_name=_("RNZAF"),
205
        help_text=_("Royal New Zealand Air Force"),
206
    )
207 1
    saf = AirForce(
208
        country=Countries.sk,
209
        default_flight_prefix='sk01',
210
        value='sk',
211
        verbose_name=_("SAF"),
212
        help_text=_("Slovak Air Force"),
213
    )
214 1
    usaaf = AirForce(
215
        country=Countries.us,
216
        default_flight_prefix='usa01',
217
        value='us',
218
        verbose_name=_("USAAF"),
219
        help_text=_("United States Army Air Forces"),
220
    )
221 1
    usmc = AirForce(
222
        country=Countries.us,
223
        default_flight_prefix='UM_NN',
224
        value='um',
225
        verbose_name=_("USMC"),
226
        help_text=_("United States Marine Corps"),
227
    )
228 1
    usn = AirForce(
229
        country=Countries.us,
230
        default_flight_prefix='UN_NN',
231
        value='un',
232
        verbose_name=_("USN"),
233
        help_text=_("United States Navy"),
234
    )
235 1
    vvs_rkka = AirForce(
236
        country=Countries.su,
237
        default_flight_prefix='r01',
238
        value='ru',
239
        verbose_name=_("VVS RKKA"),
240
        help_text=_("Workers-Peasants Red Army Air Forces"),
241
    )
242 1
    none = AirForce(
243
        country=None,
244
        default_flight_prefix=None,
245
        value='nn',
246
        verbose_name=_("None"),
247
    )
248
249 1
    @classmethod
250
    def get_flight_prefixes(cls):
251 1
        result = map(lambda x: x.default_flight_prefix, cls.iterconstants())
252 1
        if six.PY3:
253 1
            result = list(result)
254 1
        return result
255
256 1
    @classmethod
257
    def get_by_flight_prefix(cls, prefix):
258 1
        for constant in cls.iterconstants():
259 1
            if constant.default_flight_prefix == prefix:
260 1
                return constant
261 1
        raise ValueError(
262
            "Air force with prefix '{0}' is not present in '{1}'"
263
            .format(prefix, cls.__name__)
264
        )
265
266 1
    @classmethod
267
    def filter_by_country(cls, country):
268 1
        return filter(lambda x: x.country == country, cls.constants())
269
270 1
    @classmethod
271
    def filter_by_belligerent(cls, belligerent):
272 1
        return filter(
273
            lambda x: x.country.belligerent == belligerent if x.country else False,
274
            cls.constants()
275
        )
276
277
278 1
def _get_data_file_path(file_name):
279 1
    root = os.path.dirname(os.path.abspath(__file__))
280 1
    return os.path.join(root, 'data', file_name)
281
282
283 1
class Regiment(object):
284
285 1
    def __init__(self, air_force, code_name):
286 1
        self.air_force = air_force
287 1
        self.code_name = str(code_name)
288
289 1
    def __getattr__(self, name):
290 1
        if name == 'verbose_name':
291 1
            getter = self._get_verbose_name
292 1
        elif name == 'help_text':
293 1
            getter = self._get_help_text
294
        else:
295 1
            raise AttributeError("%r object has no attribute %r"
296
                                 % (self.__class__, name))
297
298 1
        language = get_language()
299 1
        final_name = "{0}_{1}".format(name, language)
300
301 1
        if hasattr(self, final_name):
302
            return getattr(self, final_name)
303
304
        # Check language code is known
305 1
        default_language = SupportedLanguages.get_default().name
306 1
        if language not in SupportedLanguages:
307 1
            language = default_language
308
309
        # Try to get value for specified language or for default language
310 1
        value = getter(language)
311 1
        if not value and language != default_language:
312 1
            value = getter(default_language)
313
314
        # Add missing attribute to the object
315 1
        setattr(self, final_name, value)
316 1
        return value
317
318 1
    def _get_verbose_name(self, language):
319 1
        file_name = "regShort_{0}.properties".format(language)
320 1
        return self._get_text(file_name)
321
322 1
    def _get_help_text(self, language):
323 1
        file_name = "regInfo_{0}.properties".format(language)
324 1
        return self._get_text(file_name)
325
326 1
    def _get_text(self, file_name):
327 1
        file_path = _get_data_file_path(file_name)
328
329 1
        with open(file_path, mode='r', encoding='cp1251') as f:
330 1
            for line in f:
331 1
                if line.startswith(self.code_name):
332 1
                    start = len(self.code_name)
333 1
                    result = line[start:].strip()
334 1
                    if six.PY3:
335 1
                        result = bytes(result, 'ascii')
336 1
                    return result.decode('unicode-escape')
337 1
        return ''
338
339 1
    def to_primitive(self, context=None):
340
        """
341
        Add for consistency with constants.
342
        """
343 1
        return {
344
            'air_force': self.air_force.to_primitive(context),
345
            'code_name': self.code_name,
346
            'verbose_name': six.text_type(self.verbose_name),
347
            'help_text': six.text_type(self.help_text),
348
        }
349
350
    def __repr__(self):
351
        return "<Regiment '{:}'>".format(self.code_name)
352
353
354 1
class Regiments(object):
355
356 1
    _cache = {}
357 1
    _file_name = 'regiments.ini'
358
359 1
    def __new__(cls):
360 1
        raise TypeError("'{0}' may not be instantiated".format(cls.__name__))
361 View Code Duplication
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
362 1
    @classmethod
363
    def get_by_code_name(cls, code_name):
364 1
        if code_name in cls._cache:
365 1
            return cls._cache[code_name]
366
367 1
        flight_prefixes = AirForces.get_flight_prefixes()
368 1
        last_flight_prefix = None
369 1
        found = False
370
371 1
        file_path = _get_data_file_path(cls._file_name)
372 1
        with open(file_path, mode='r', encoding='cp1251') as f:
373 1
            for line in f:
374 1
                line = line.strip()
375 1
                if not line:
376 1
                    continue
377 1
                if line in flight_prefixes:
378 1
                    last_flight_prefix = line
379 1
                    continue
380 1
                if line == code_name:
381 1
                    found = True
382 1
                    break
383
384 1
        if found and last_flight_prefix:
385 1
            air_force = AirForces.get_by_flight_prefix(last_flight_prefix)
386 1
            regiment = Regiment(air_force, code_name)
387 1
            cls._cache[code_name] = regiment
388 1
            return regiment
389
390 1
        raise ValueError("Regiment with code name '{0}' is unknown"
391
                         .format(code_name))
392 View Code Duplication
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
393 1
    @classmethod
394
    def filter_by_air_force(cls, air_force):
395 1
        result = []
396
397 1
        flight_prefixes = AirForces.get_flight_prefixes()
398 1
        found = False
399
400 1
        file_path = _get_data_file_path(cls._file_name)
401 1
        with open(file_path, mode='r', encoding='cp1251') as f:
402 1
            for line in f:
403 1
                line = line.strip()
404
405 1
                if not line:
406 1
                    continue
407
408 1
                if line == air_force.default_flight_prefix:
409
                    # Flag that proper section was found.
410 1
                    found = True
411 1
                    continue
412
413 1
                if found:
414 1
                    if (
415
                        line in flight_prefixes
416
                        or (line.startswith('[') and line.endswith(']'))
417
                    ):
418
                        # Next section was found. Fullstop.
419 1
                        break
420
421 1
                    if line in cls._cache:
422 1
                        regiment = cls._cache[line]
423
                    else:
424 1
                        regiment = Regiment(air_force, line)
425 1
                        cls._cache[line] = regiment
426
427 1
                    result.append(regiment)
428
429
        return result
430