<!DOCTYPE html>
<html>

  <head>
    <base href="." />
    <title>angular2 playground</title>
    <link rel="stylesheet" href="style.css" />
    <script src="https://unpkg.com/core-js@2.4.1/client/shim.min.js"></script>
    <script src="https://unpkg.com/zone.js/dist/zone.js"></script>
    <script src="https://unpkg.com/zone.js/dist/long-stack-trace-zone.js"></script>
    <script src="https://unpkg.com/reflect-metadata@0.1.3/Reflect.js"></script>
    <script src="https://unpkg.com/systemjs@0.19.31/dist/system.js"></script>
    <script src="config.js"></script>
    <script>
    System.import('app')
      .catch(console.error.bind(console));
  </script>
  </head>

  <body>
    <my-app>
    loading...
    </my-app>
  </body>

</html>
System.config({
  //use typescript for compilation
  transpiler: 'typescript',
  //typescript compiler options
  typescriptOptions: {
    emitDecoratorMetadata: true
  },
  paths: {
    'npm:': 'https://unpkg.com/'
  },
  //map tells the System loader where to look for things
  map: {
    
    'app': './src',
    
    '@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-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/forms': 'npm:@angular/forms/bundles/forms.umd.js',
    
    '@angular/core/testing': 'npm:@angular/core/bundles/core-testing.umd.js',
    '@angular/common/testing': 'npm:@angular/common/bundles/common-testing.umd.js',
    '@angular/compiler/testing': 'npm:@angular/compiler/bundles/compiler-testing.umd.js',
    '@angular/platform-browser/testing': 'npm:@angular/platform-browser/bundles/platform-browser-testing.umd.js',
    '@angular/platform-browser-dynamic/testing': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic-testing.umd.js',
    '@angular/http/testing': 'npm:@angular/http/bundles/http-testing.umd.js',
    '@angular/router/testing': 'npm:@angular/router/bundles/router-testing.umd.js',
    
    'rxjs': 'npm:rxjs',
    'typescript': 'npm:typescript@2.0.2/lib/typescript.js'
  },
  //packages defines our app package
  packages: {
    app: {
      main: './main.ts',
      defaultExtension: 'ts'
    },
    rxjs: {
      defaultExtension: 'js'
    }
  }
});
//main entry point
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {AppModule} from './app';

platformBrowserDynamic().bootstrapModule(AppModule)
//our root app component
import {Component, NgModule, OnInit, Input, Injectable, Directive, HostListener, ViewChild, AfterContentChecked} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

@Injectable()
export class MyModalService {
  map: Map<string, MyModalComponent> = new Map

  get(v: string): MyModalComponent {
    return this.map.get(v)
  }

  set(key: string, v: MyModalComponent): void {
    this.map.set(key, v)
  }
}

@Component({
  selector: 'my-modal',
  template: `
    <div class="reveal-overlay" (click)="clickOverlay($event)" [hidden]="!show">
      <div class="reveal">
        <div #modalContent>
          <ng-content></ng-content>
        </div>
        <button class="close-button" (click)="toggle()">
          <span>&times;</span>
        </button>
      </div>
    </div>
  `,
  styles: [
    '.reveal-overlay { background: rgba(0,0,0,0.6); position: fixed; top: 0; left: 0; right: 0; bottom: 0; }',
    '.reveal { background: white; width: 90%; margin: 40px auto; min-height: 70vh; position: relative; padding: 20px; }'
    '.close-button { position: absolute; right: 10px; top: 10px; }'
    ]
})
export class MyModalComponent implements OnInit, DoCheck {
  @Input() name: string
  @ViewChild('modalContent') modalContent

  private show: boolean = false
  // store elements to notify 
  private notify: HTMLElements[] = [] 

  constructor(private myModals: MyModalService) { }

  ngOnInit() {
    this.myModals.set(this.name, this)
  }

  clickOverlay(event: Event) {
    const target = (event.target as HTMLElement)

    if (target.classList.contains('reveal-overlay')) {
      this.toggle()
    }
  }

  toggle() {
    this.show = !this.show

    if (this.show) {
      document.addEventListener('keyup', this.escapeListener)
    } else {
      document.removeEventListener('keyup', this.escapeListener)
    }
    
    this.notify = [].slice.call(this.modalContent.nativeElement.children)
  }
  
  ngAfterContentChecked() {
    if (this.notify.length === 0) {
      return
    }

    const event = this.createEvent(this.show ? 'modalOpen' : 'modalClose')
    let toNotify

    while(toNotify = this.notify.shift()) {
      toNotify.dispatchEvent(event)
    }
  }

  private createEvent(name) {
    const event = document.createEvent('Events')
    event.initEvent(name, true, true)
    return event
  }


  private escapeListener = (event: KeyboardEvent) => {
    if (event.which === 27 || event.keyCode === 27) {
      this.show = false
    }
  }
}

@Directive({
  selector: '[myModalOpen]'
})
export class MyModalOpenDirective {
  @Input() myModalOpen: string

  constructor(private myModals: MyModalService) {
  }

  @HostListener('click') onClick() {
    const modal = this.myModals.get(this.myModalOpen)

    if (!modal) {
      console.error('No modal named %s', this.myModalOpen)
      return
    }
    
    modal.toggle()
  }
}

@Component({
  selector: 'my-custom-component',
  template: '<p>{{foo}}</p>'
})
export class MyCustomComponent {
  @Input() foo: string
  @HostListener('modalOpen') onModalOpen() {
    this.foo = this.foo.split('').reverse().join('')
  }
}


@Component({
  selector: 'my-app',
  template: `
    <my-modal name="hello world">
      <my-custom-component [foo]="foo"></my-custom-component>
    </my-modal>
    <button myModalOpen="hello world">Open !</button>
  `,
})
export class App {
  foo = 'hello world'
}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App, MyModalComponent, MyModalOpenDirective, MyCustomComponent ],
  providers: [ MyModalService ]
  bootstrap: [ App ]
})
export class AppModule {}