import { Component } from '@angular/core';
import { DawaAutocompleteItem } from 'ngx-dawa-autocomplete';

@Component({
  selector: 'my-app',
  template: `
        <div class="autocomplete-container">
            <input
                type="text"
                [value]="selectedStreet"
                ngxDawaAutocomplete
                (items$)="onItems($event)"
                (highlighted$)="onItemHighlighted($event)"
                (select$)="onItemSelected($event)" />
            <ul class="autocomplete-items" *ngIf="items.length > 0">
                <li class="autocomplete-item"
                    *ngFor="let item of items; let i = index;"
                    [class.highlighted]="i === highlightedIndex"
                    (click)="onItemSelected(item)">
                    {{item.text}}
                </li>
            </ul>
        </div>
  `,
  styles: [ `
      input {
        border: 1px solid #ccc;
        background: #f9f9f9;
        box-shadow: inset 0 0 0 #fff;
        padding: 0.4em;
        font-size: 15px;
        width: 100%;
        box-sizing: border-box;
      }
      input:focus {
        outline: none;
      }
      .autocomplete-container {
      position: relative;
      width:400px;
      }
      .autocomplete-items {
        list-style: none;
          padding: 0.2em 0;
          margin: 0;
          position: absolute;
          z-index: 50;
          margin-top: 0px;
          left: 0;
          right: 0;
          background-color: #ffffff;
          border: 1px solid rgba(0, 0, 0, 0.2);
          box-shadow: 0 5px 10px rgba(0, 0, 0, 0.1);
          border-top-color: transparent;
      }
      .autocomplete-item {
          cursor: pointer;
          padding: 0.5em 1em;
          border-bottom: 1px solid whitesmoke;
      }
      .autocomplete-item:last-child {
          border-bottom: none;
      }
      .autocomplete-item:hover,
      .autocomplete-item.highlighted {
          background-color: #f9f9f9;
          font-weight: bold;
      }
  `]
})
export class AppComponent {

    public items: DawaAutocompleteItem[] = [];
    public highlightedIndex: number = 0;
    public selectedStreet: string = '';

    public onItems(items) {
        this.items = items;
    }

    public onItemHighlighted(index) {
        this.highlightedIndex = index;
    }

    public onItemSelected(item) {
        this.items = [];
        this.highlightedIndex = 0;
        this.selectedStreet = item.fullStreet;
    }
}
import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpModule } from '@angular/http';

import { AppComponent }  from './app.component';

import { DawaAutocompleteDirective } from './dawa-autocomplete.directive';
import { DawaAutocompleteService } from './dawa-autocomplete.service';

@NgModule({
  imports:      [ BrowserModule, HttpModule ],
  declarations: [ AppComponent, DawaAutocompleteDirective ],
  bootstrap:    [ AppComponent ],
  providers:    [ DawaAutocompleteService ]
})
export class AppModule { }
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';

platformBrowserDynamic().bootstrapModule(AppModule);


/*
Copyright 2017 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
*/
<!DOCTYPE html>
<html>
  <head>
    <title>Angular Quickstart</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
      body {color:#369;font-family: Arial,Helvetica,sans-serif;}
    </style>

    <!-- Polyfills -->
    <script src="https://unpkg.com/core-js/client/shim.min.js"></script>

    <script src="https://unpkg.com/zone.js@0.8.4?main=browser"></script>
    <script src="https://unpkg.com/systemjs@0.19.39/dist/system.src.js"></script>
    <script src="systemjs.config.js"></script>
    <script>
      System.import('main.js').catch(function(err){ console.error(err); });
    </script>
  </head>

  <body>
    <my-app>Loading AppComponent content here ...</my-app>
  </body>

</html>


<!-- 
Copyright 2017 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
-->
/**
 * WEB ANGULAR VERSION
 * (based on systemjs.config.js in angular.io)
 * System configuration for Angular samples
 * Adjust as necessary for your application needs.
 */
(function (global) {
  System.config({
    // DEMO ONLY! REAL CODE SHOULD NOT TRANSPILE IN THE BROWSER
    transpiler: 'ts',
    typescriptOptions: {
      // Copy of compiler options in standard tsconfig.json
      "target": "es5",
      "module": "commonjs",
      "moduleResolution": "node",
      "sourceMap": true,
      "emitDecoratorMetadata": true,
      "experimentalDecorators": true,
      "lib": ["es2015", "dom"],
      "noImplicitAny": true,
      "suppressImplicitAnyIndexErrors": true
    },
    meta: {
      'typescript': {
        "exports": "ts"
      }
    },
    paths: {
      // paths serve as alias
      'npm:': 'https://unpkg.com/'
    },
    // map tells the System loader where to look for things
    map: {
      // our app is within the app folder
      'app': 'app',

      // angular bundles
      '@angular/animations': 'npm:@angular/animations/bundles/animations.umd.js',
      '@angular/animations/browser': 'npm:@angular/animations/bundles/animations-browser.umd.js',
      '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
      '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
      '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
      '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
      '@angular/platform-browser/animations': 'npm:@angular/platform-browser/bundles/platform-browser-animations.umd.js',
      '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
      '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
      '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
      '@angular/router/upgrade': 'npm:@angular/router/bundles/router-upgrade.umd.js',
      '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
      '@angular/upgrade': 'npm:@angular/upgrade/bundles/upgrade.umd.js',
      '@angular/upgrade/static': 'npm:@angular/upgrade/bundles/upgrade-static.umd.js',

      // other libraries
      'rxjs':                      'npm:rxjs@5.0.1',
      'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js',
      'ts':                        'npm:plugin-typescript@5.2.7/lib/plugin.js',
      'typescript':                'npm:typescript@2.2.1/lib/typescript.js',

    },
    // packages tells the System loader how to load when no filename and/or no extension
    packages: {
      app: {
        main: './main.ts',
        defaultExtension: 'ts',
        meta: {
          './*.ts': {
            loader: 'systemjs-angular-loader.js'
          }
        }
      },
      rxjs: {
        defaultExtension: 'js'
      }
    }
  });

})(this);

/*
Copyright 2016 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
*/
var templateUrlRegex = /templateUrl\s*:(\s*['"`](.*?)['"`]\s*)/gm;
var stylesRegex = /styleUrls *:(\s*\[[^\]]*?\])/g;
var stringRegex = /(['`"])((?:[^\\]\\\1|.)*?)\1/g;

module.exports.translate = function(load){
  if (load.source.indexOf('moduleId') != -1) return load;

  var url = document.createElement('a');
  url.href = load.address;

  var basePathParts = url.pathname.split('/');

  basePathParts.pop();
  var basePath = basePathParts.join('/');

  var baseHref = document.createElement('a');
  baseHref.href = this.baseURL;
  baseHref = baseHref.pathname;

  if (!baseHref.startsWith('/base/')) { // it is not karma
    basePath = basePath.replace(baseHref, '');
  }

  load.source = load.source
    .replace(templateUrlRegex, function(match, quote, url){
      let resolvedUrl = url;

      if (url.startsWith('.')) {
        resolvedUrl = basePath + url.substr(1);
      }

      return 'templateUrl: "' + resolvedUrl + '"';
    })
    .replace(stylesRegex, function(match, relativeUrls) {
      var urls = [];

      while ((match = stringRegex.exec(relativeUrls)) !== null) {
        if (match[2].startsWith('.')) {
          urls.push('"' + basePath + match[2].substr(1) + '"');
        } else {
          urls.push('"' + match[2] + '"');
        }
      }

      return "styleUrls: [" + urls.join(', ') + "]";
    });

  return load;
};
import { Directive, AfterViewInit, OnDestroy, Output, EventEmitter, HostListener, ElementRef } from '@angular/core';

import { Observable } from 'rxjs/Observable';
import { Subscription } from 'rxjs/Subscription';

import 'rxjs/add/observable/fromEvent';
import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/switchMap';

import { DawaAutocompleteService, DawaAutocompleteItem } from './dawa-autocomplete.service';

@Directive({
    selector: '[ngxDawaAutocomplete]'
})
export class DawaAutocompleteDirective implements AfterViewInit, OnDestroy {

    @Output() items$: EventEmitter<DawaAutocompleteItem[]> = new EventEmitter<DawaAutocompleteItem[]>();
    @Output() highlighted$: EventEmitter<number> = new EventEmitter<number>();
    @Output() select$: EventEmitter<DawaAutocompleteItem> = new EventEmitter<DawaAutocompleteItem>();

    private _searchEventSubscription$: Subscription;
    private _arrowEventSubscription$: Subscription;
    private _selectEventSubscription$: Subscription;

    private _items: DawaAutocompleteItem[] = [];
    private _highlightedIndex = 0;

    constructor(private _elementRef: ElementRef,
                private _dawaAutocompleteService: DawaAutocompleteService) {}

    public ngAfterViewInit() {

        this._searchEventSubscription$ = Observable
            .fromEvent(this._elementRef.nativeElement, 'keyup')
            .filter(this.filterArrowEnterAndTabKeys)
            .map(e => e.target.value)
            .debounceTime(150)
            .distinctUntilChanged()
            .switchMap((term: string) => this._dawaAutocompleteService.search(term))
            .subscribe(items => {

                this._items = items;
                this._highlightedIndex = 0;

                this.highlighted$.next(this._highlightedIndex);
                this.items$.next(this._items);
            });

        const keydownEvent$ = Observable
            .fromEvent<KeyboardEvent>(this._elementRef.nativeElement.parentElement, 'keydown');

        this._arrowEventSubscription$ = keydownEvent$
            .filter(e => e.keyCode === 38 || e.keyCode === 40)
            .subscribe(e => {

                e.preventDefault();

                if (e.keyCode === 40) {
                    this._highlightedIndex = this._highlightedIndex === (this._items.length - 1) ? 0 : this._highlightedIndex + 1;
                } else if (e.keyCode === 38) {
                    this._highlightedIndex = this._highlightedIndex <= 0 ? (this._items.length - 1) : this._highlightedIndex - 1;
                }

                this.highlighted$.next(this._highlightedIndex);
            });

        this._selectEventSubscription$ = keydownEvent$
            .filter(e => e.keyCode === 13 || e.keyCode === 9)
            .subscribe(e => {

                if (this._items[this._highlightedIndex]) {
                    this.select$.next(this._items[this._highlightedIndex]);
                }
            });
    }

    public ngOnDestroy() {

        this._searchEventSubscription$.unsubscribe();
        this._arrowEventSubscription$.unsubscribe();
        this._selectEventSubscription$.unsubscribe();
    }

    @HostListener('click', ['$event'])
    public onClick(event) {

        this._dawaAutocompleteService
            .search(event.target.value)
            .subscribe(items => {
                this._items = items;
                this._highlightedIndex = 0;
                this.items$.next(this._items);
            });
    }

    @HostListener('focus', ['$event'])
    public onFocus(event) {

        this._dawaAutocompleteService
            .search(event.target.value)
            .subscribe(items => {
                this._items = items;
                this._highlightedIndex = 0;
                this.items$.next(this._items);
            });
    }

    @HostListener('document:click', ['$event.target'])
    public onOutsideClick(target) {

        if (!this._elementRef.nativeElement.parentElement.contains(target)) {
            this._highlightedIndex = 0;
            this.items$.next([]);
        }
    }

    private filterArrowEnterAndTabKeys(event) {
        return event.keyCode !== 37 &&
               event.keyCode !== 38 &&
               event.keyCode !== 39 &&
               event.keyCode !== 40 &&
               event.keyCode !== 13 &&
               event.keyCode !== 9;
    }
}
import { Injectable } from '@angular/core';
import { Http, URLSearchParams } from '@angular/http';
import { Observable } from 'rxjs/Observable';

import 'rxjs/add/observable/of';

@Injectable()
export class DawaAutocompleteService {

    constructor(private _http: Http) {}

    search(searchTerm: string): Observable<DawaAutocompleteItem[]> {

        const searchQuery = new URLSearchParams();
        searchQuery.set('q', searchTerm);
        searchQuery.set('per_side', '6');
        searchQuery.set('format', 'json');

        if (searchTerm) {
            return this._http
                        .get('https://dawa.aws.dk/adresser/autocomplete', { search: searchQuery })
                        .map((request) => request.json())
                        .map(this.mapToAutocompleteItem);
        }

        return Observable.of([]);
    }

    private mapToAutocompleteItem(items: any[]): DawaAutocompleteItem[] {
        return items.map(item => {
            return {
                text: item.tekst,
                door: item.adresse['dør'],
                floor: item.adresse['etage'],
                number: item.adresse['husnr'],
                zip: item.adresse['postnr'],
                city: item.adresse['postnrnavn'],
                street: item.adresse['vejnavn'],
                fullStreet: item.tekst.lastIndexOf(',') > 0 ? item.tekst.substring(0, item.tekst.lastIndexOf(',')) : item.tekst
            };
        });
    }
}

export class DawaAutocompleteItem {
    text: string;
    door: string;
    floor: string;
    number: string;
    zip: number;
    city: string;
    street: string;
    fullStreet: string;
}