Test Failed
Push — develop ( 836cd9...6ec826 )
by Endre
15:03
created

Registry.getPages   A

Complexity

Conditions 1

Size

Total Lines 11
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 10
dl 0
loc 11
rs 9.9
c 0
b 0
f 0
1
import ListenerAdapter from '../Observer/ListenerAdapter';
2
import {IObserver} from '../Observer/Observer';
3
import {IPageData} from './Router';
4
5
interface IRegistryPageData {
6
  page: IPageData,
7
  sourceUrl: string,
8
}
9
10
export interface IPageDictionary<T> {
11
  [index: string]: T
12
}
13
14
export default class Registry {
15
  dictionary: IPageDictionary<IRegistryPageData>;
16
  adapter: ListenerAdapter<IPageData>;
17
  observer: IObserver<IPageData>;
18
19
  constructor(observer: IObserver<IPageData>, adapter: ListenerAdapter<IPageData>) {
20
    this.observer = observer;
21
    this.adapter = adapter;
22
    this.dictionary = {};
23
24
    this.adapter.addListener(this.updatePageData.bind(this));
25
  }
26
27
  getPages(): IPageDictionary<IPageData> {
28
    const pages: IPageDictionary<IPageData> = {};
29
30
    Object.keys(this.dictionary).forEach((pageName: string) => {
31
      const registeredPage: IRegistryPageData = this.dictionary[pageName];
32
      const page: IPageData = registeredPage.page;
33
      pages[page.name] = page;
34
    });
35
36
    return pages;
37
  }
38
39
  registerPage(page: IPageData) {
40
    const registeredPage: IRegistryPageData = {
41
      page: page,
42
      sourceUrl: page.url
43
    };
44
45
    this.updatePageUrlByDepth(registeredPage, this.observer.value.depth, false);
46
    this.dictionary[page.name] = registeredPage;
47
  }
48
49
  protected updatePageData(oldValue: IPageData, newValue: IPageData): void {
50
    Object.keys(this.dictionary).forEach(
51
      (pageName: string) => {
52
        this.updatePageUrlByDepth(this.dictionary[pageName], newValue.depth, newValue.name == pageName);
53
      }
54
    );
55
  }
56
57
  protected updatePageUrlByDepth(registeredPage: IRegistryPageData, depth: number, removeDirectory: boolean): void {
58
    let relativeBack: string = '', index: number = 0, newUrl: string = '';
59
60
    if (removeDirectory) {
61
      newUrl = registeredPage.sourceUrl.replace(/.*\//, './');
62
    } else {
63
      for (index = 0; index < depth; index++) {
64
        relativeBack += '../';
65
      }
66
      newUrl = (relativeBack + registeredPage.sourceUrl).replace('.././', '../');
67
    }
68
69
    registeredPage.page.url = newUrl;
70
  }
71
}