Completed
Push — master ( 7ba3d3...51f7d3 )
by Oleksandr
01:52
created

AirForces.get_by_flight_prefix()   A

Complexity

Conditions 3

Size

Total Lines 8

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 8
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 1
    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
        help_text=_("German Air Force"),
144
    )
145 1
    ija = AirForce(
146
        country=Countries.jp,
147
        default_flight_prefix='ja01',
148
        value='ja',
149
        verbose_name=_("IJA"),
150
        help_text=_("Imperial Japanese Army"),
151
    )
152 1
    ijn = AirForce(
153
        country=Countries.jp,
154
        default_flight_prefix='IN_NN',
155
        value='in',
156
        verbose_name=_("IJN"),
157
        help_text=_("Imperial Japanese Navy"),
158
    )
159 1
    paf = AirForce(
160
        country=Countries.pl,
161
        default_flight_prefix='pl01',
162
        value='pl',
163
        verbose_name=_("PAF"),
164
        help_text=_("Polish Air Force"),
165
    )
166 1
    rai = AirForce(
167
        country=Countries.it,
168
        default_flight_prefix='i01',
169
        value='it',
170
        verbose_name=_("RAI"),
171
        help_text=_("Regia Aeronautica Italiana"),
172
    )
173 1
    raaf = AirForce(
174
        country=Countries.au,
175
        default_flight_prefix='RA_NN',
176
        value='ra',
177
        verbose_name=_("RAAF"),
178
        help_text=_("Royal Australian Air Force"),
179
    )
180 1
    raf = AirForce(
181
        country=Countries.uk,
182
        default_flight_prefix='gb01',
183
        value='gb',
184
        verbose_name=_("RAF"),
185
        help_text=_("Royal Air Force"),
186
    )
187 1
    rn = AirForce(
188
        country=Countries.uk,
189
        default_flight_prefix='RN_NN',
190
        value='rn',
191
        verbose_name=_("RN"),
192
        help_text=_("Royal Navy"),
193
    )
194 1
    rnlaf = AirForce(
195
        country=Countries.nl,
196
        default_flight_prefix='DU_NN',
197
        value='du',
198
        verbose_name=_("RNLAF"),
199
        help_text=_("Royal Netherlands Air Force"),
200
    )
201 1
    rnzaf = AirForce(
202
        country=Countries.nz,
203
        default_flight_prefix='RZ_NN',
204
        value='rz',
205
        verbose_name=_("RNZAF"),
206
        help_text=_("Royal New Zealand Air Force"),
207
    )
208 1
    saf = AirForce(
209
        country=Countries.sk,
210
        default_flight_prefix='sk01',
211
        value='sk',
212
        verbose_name=_("SAF"),
213
        help_text=_("Slovak Air Force"),
214
    )
215 1
    usaaf = AirForce(
216
        country=Countries.us,
217
        default_flight_prefix='usa01',
218
        value='us',
219
        verbose_name=_("USAAF"),
220
        help_text=_("United States Army Air Forces"),
221
    )
222 1
    usmc = AirForce(
223
        country=Countries.us,
224
        default_flight_prefix='UM_NN',
225
        value='um',
226
        verbose_name=_("USMC"),
227
        help_text=_("United States Marine Corps"),
228
    )
229 1
    usn = AirForce(
230
        country=Countries.us,
231
        default_flight_prefix='UN_NN',
232
        value='un',
233
        verbose_name=_("USN"),
234
        help_text=_("United States Navy"),
235
    )
236 1
    vvs_rkka = AirForce(
237
        country=Countries.su,
238
        default_flight_prefix='r01',
239
        value='ru',
240
        verbose_name=_("VVS RKKA"),
241
        help_text=_("Workers-Peasants Red Army Air Forces"),
242
    )
243 1
    none = AirForce(
244
        country=None,
245
        default_flight_prefix=None,
246
        value='nn',
247
        verbose_name=_("None"),
248
        help_text=_("No Air Force"),
249
    )
250
251 1
    @classmethod
252
    def get_flight_prefixes(cls):
253 1
        result = map(lambda x: x.default_flight_prefix, cls.iterconstants())
254 1
        if six.PY3:
255
            result = list(result)
256 1
        return result
257
258 1
    @classmethod
259
    def get_by_flight_prefix(cls, prefix):
260 1
        for constant in cls.iterconstants():
261 1
            if constant.default_flight_prefix == prefix:
262 1
                return constant
263 1
        raise ValueError(
264
            "Air force with prefix '{0}' is not present in '{1}'"
265
            .format(prefix, cls.__name__)
266
        )
267
268 1
    @classmethod
269
    def filter_by_country(cls, country):
270 1
        return filter(lambda x: x.country == country, cls.constants())
271
272 1
    @classmethod
273
    def filter_by_belligerent(cls, belligerent):
274 1
        return filter(
275
            lambda x: x.country.belligerent == belligerent if x.country else False,
276
            cls.constants()
277
        )
278
279
280 1
def _get_data_file_path(file_name):
281 1
    root = os.path.dirname(os.path.abspath(__file__))
282 1
    return os.path.join(root, 'data', file_name)
283
284
285 1
class Regiment(object):
286
287 1
    def __init__(self, air_force, code_name):
288 1
        self.air_force = air_force
289 1
        self.code_name = str(code_name)
290
291 1
    def __getattr__(self, name):
292 1
        if name == 'verbose_name':
293 1
            getter = self._get_verbose_name
294 1
        elif name == 'help_text':
295 1
            getter = self._get_help_text
296
        else:
297 1
            raise AttributeError("%r object has no attribute %r"
298
                                 % (self.__class__, name))
299
300 1
        language = get_language()
301 1
        final_name = "{0}_{1}".format(name, language)
302
303 1
        if hasattr(self, final_name):
304
            return getattr(self, final_name)
305
306
        # Check language code is known
307 1
        default_language = SupportedLanguages.get_default().name
308 1
        if language not in SupportedLanguages:
309 1
            language = default_language
310
311
        # Try to get value for specified language or for default language
312 1
        value = getter(language)
313 1
        if not value and language != default_language:
314 1
            value = getter(default_language)
315
316
        # Add missing attribute to the object
317 1
        setattr(self, final_name, value)
318 1
        return value
319
320 1
    def _get_verbose_name(self, language):
321 1
        file_name = "regShort_{0}.properties".format(language)
322 1
        return self._get_text(file_name)
323
324 1
    def _get_help_text(self, language):
325 1
        file_name = "regInfo_{0}.properties".format(language)
326 1
        return self._get_text(file_name)
327
328 1
    def _get_text(self, file_name):
329 1
        file_path = _get_data_file_path(file_name)
330
331 1
        with open(file_path, mode='r', encoding='cp1251') as f:
332 1
            for line in f:
333 1
                if line.startswith(self.code_name):
334 1
                    start = len(self.code_name)
335 1
                    result = line[start:].strip()
336 1
                    if six.PY3:
337
                        result = bytes(result, 'ascii')
338 1
                    return result.decode('unicode-escape')
339 1
        return ''
340
341 1
    def to_primitive(self, context=None):
342
        """
343
        Add for consistency with constants.
344
        """
345 1
        return {
346
            'air_force': self.air_force.to_primitive(context),
347
            'code_name': self.code_name,
348
            'verbose_name': six.text_type(self.verbose_name),
349
            'help_text': six.text_type(self.help_text),
350
        }
351
352
    def __repr__(self):
353
        return "<Regiment '{:}'>".format(self.code_name)
354
355
356 1
class Regiments(object):
357
358 1
    _cache = {}
359 1
    _file_name = 'regiments.ini'
360
361 1 View Code Duplication
    def __new__(cls):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
362 1
        raise TypeError("'{0}' may not be instantiated".format(cls.__name__))
363
364 1
    @classmethod
365
    def get_by_code_name(cls, code_name):
366 1
        if code_name in cls._cache:
367 1
            return cls._cache[code_name]
368
369 1
        flight_prefixes = AirForces.get_flight_prefixes()
370 1
        last_flight_prefix = None
371 1
        found = False
372
373 1
        file_path = _get_data_file_path(cls._file_name)
374 1
        with open(file_path, mode='r', encoding='cp1251') as f:
375 1
            for line in f:
376 1
                line = line.strip()
377 1
                if not line:
378 1
                    continue
379 1
                if line in flight_prefixes:
380 1
                    last_flight_prefix = line
381 1
                    continue
382 1
                if line == code_name:
383 1
                    found = True
384 1
                    break
385
386 1
        if found and last_flight_prefix:
387 1
            air_force = AirForces.get_by_flight_prefix(last_flight_prefix)
388 1
            regiment = Regiment(air_force, code_name)
389 1
            cls._cache[code_name] = regiment
390 1
            return regiment
391
392 1 View Code Duplication
        raise ValueError("Regiment with code name '{0}' is unknown"
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
393
                         .format(code_name))
394
395 1
    @classmethod
396
    def filter_by_air_force(cls, air_force):
397 1
        result = []
398
399 1
        flight_prefixes = AirForces.get_flight_prefixes()
400 1
        found = False
401
402 1
        file_path = _get_data_file_path(cls._file_name)
403 1
        with open(file_path, mode='r', encoding='cp1251') as f:
404 1
            for line in f:
405 1
                line = line.strip()
406
407 1
                if not line:
408 1
                    continue
409
410 1
                if line == air_force.default_flight_prefix:
411
                    # Flag that proper section was found.
412 1
                    found = True
413 1
                    continue
414
415 1
                if found:
416 1
                    if (
417
                        line in flight_prefixes
418
                        or (line.startswith('[') and line.endswith(']'))
419
                    ):
420
                        # Next section was found. Fullstop.
421 1
                        break
422
423 1
                    if line in cls._cache:
424 1
                        regiment = cls._cache[line]
425
                    else:
426 1
                        regiment = Regiment(air_force, line)
427 1
                        cls._cache[line] = regiment
428
429 1
                    result.append(regiment)
430
431
        return result
432