blob: 44d3cdc68c1c0c871c6d6cc1a4fc5dfcd61499ac [file] [log] [blame]
Matteo Scandolod58d5042016-12-16 16:59:21 -08001import * as _ from 'lodash';
2import * as pluralize from 'pluralize';
3import {IXosTableColumn} from '../../table/table';
4
5export interface IXosModelDefsField {
6 name: string;
7 type: string;
8}
9
10export interface IXosConfigHelpersService {
11 modeldefToTableCfg(fields: IXosModelDefsField[]): any[]; // TODO use a proper interface
12 pluralize(string: string, quantity?: number, count?: boolean): string;
13 toLabel(string: string, pluralize?: boolean): string;
14}
15
16export class ConfigHelpers {
17
18 constructor() {
19 pluralize.addIrregularRule('xos', 'xosses');
20 pluralize.addPluralRule(/slice$/i, 'slices');
21 }
22
23 pluralize(string: string, quantity?: number, count?: boolean): string {
24 return pluralize(string, quantity, count);
25 }
26
27 toLabel(string: string, pluralize?: boolean): string {
28
29 if (angular.isArray(string)) {
30 return _.map(string, s => {
31 return this.toLabel(s, pluralize);
32 });
33 }
34
35 if (pluralize) {
36 string = this.pluralize(string);
37 }
38
39 string = this.fromCamelCase(string);
40 string = this.fromSnakeCase(string);
41 string = this.fromKebabCase(string);
42
43 return this.capitalizeFirst(string);
44 }
45
46 modeldefToTableCfg(fields: IXosModelDefsField[]): IXosTableColumn[] {
47 const excluded_fields = [
48 'created',
49 'updated',
50 'enacted',
51 'policed',
52 'backend_register',
53 'deleted',
54 'write_protect',
55 'lazy_blocked',
56 'no_sync',
57 'no_policy',
58 'omf_friendly',
59 'enabled'
60 ];
61 const cfg = _.map(fields, (f) => {
62 if (excluded_fields.indexOf(f.name) > -1) {
63 return;
64 }
65 const col: IXosTableColumn = {
66 label: this.toLabel(f.name),
67 prop: f.name
68 };
69
70 if (f.name === 'backend_status') {
71 col.type = 'icon';
72 col.formatter = (item) => {
73 if (item.backend_status.indexOf('1') > -1) {
74 return 'check';
75 }
76 if (item.backend_status.indexOf('2') > -1) {
77 return 'exclamation-circle';
78 }
79 if (item.backend_status.indexOf('0') > -1) {
80 return 'clock-o';
81 }
82 };
83 }
84 return col;
85 })
86 .filter(v => angular.isDefined(v));
87
88 return cfg;
89 };
90
91 private fromCamelCase(string: string): string {
92 return string.split(/(?=[A-Z])/).map(w => w.toLowerCase()).join(' ');
93 }
94
95 private fromSnakeCase(string: string): string {
96 return string.split('_').join(' ').trim();
97 }
98
99 private fromKebabCase(string: string): string {
100 return string.split('-').join(' ').trim();
101 }
102
103 private capitalizeFirst(string: string): string {
104 return string.slice(0, 1).toUpperCase() + string.slice(1);
105 }
106}
107