import { AfterViewInit, ChangeDetectorRef, Component, NgZone, OnDestroy, OnInit, Renderer2, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';
import { ActivatedRoute, Router, UrlTree, RouterOutlet, Params } from '@angular/router';
import { MatDialog, MatDialogRef } from '@angular/material';
import { OverlayContainer } from '@angular/cdk/overlay';
import { KnkTrackKnokComponent } from '../knk-track-knok/knk-track-knok.component';
import { TokenService } from '../../shared/token/token.service';
import { IUser } from '../../shared/user';
import { UserService } from '../../shared';
import { Subject } from 'rxjs/Subject';
import { has as _has } from 'lodash/object';

@Component({
  selector: 'knk-knok-outlet',
  template: '<ng-content></ng-content>'
})
export class KnkKnokOutletComponent implements OnInit, OnDestroy, AfterViewInit {
  dialogRef: MatDialogRef<KnkTrackKnokComponent, any> = undefined;
  user: IUser = undefined;

  get id(): number {
    return +this.route.snapshot.params.id;
  }

  get userIsKnokser(): boolean {
    let userIsKnoker: boolean = false;
    if (_has(this.route.snapshot.data, ['userIsKnokser'])) {
      userIsKnoker = Boolean(this.route.snapshot.data.userIsKnokser);
    }
    return userIsKnoker;
  }

  get data(): any {
    return {id: this.id, userIsKnokser: this.userIsKnokser, router: this.router, route: this.route, outlet: this.outlet};
  }

  private ngUnsubscribe: Subject<void> = new Subject<void>();

  constructor(public dialog: MatDialog,
              public overlayContainer: OverlayContainer,
              @Inject(DOCUMENT) public document: HTMLDocument,
              private changeDetector: ChangeDetectorRef,
              private renderer: Renderer2,
              private zone: NgZone,
              private router: Router,
              private route: ActivatedRoute,
              private outlet: RouterOutlet,
              private tokenService: TokenService,
              private userService: UserService) {
  }

  ngOnInit(): void {
    this.userService.userChanged
      .takeUntil(this.ngUnsubscribe)
      .subscribe((user: IUser): void => {
        this.user = user;
        // console.warn(user);
      });
  }

  ngOnDestroy(): void {
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();

    if (this.dialogRef) {
      this.dialogRef.close(true);
    }
  }

  ngAfterViewInit(): void {
    this.route.params.debounceTime(250).subscribe((params: Params): void => {
      this.zone.run((): void => {
        const timeout: any = setTimeout((): void => {
          clearTimeout(timeout);

          if (!this.tokenService.isLogin) {
            this.outlet.deactivate();
            return;
          }

          if (this.dialogRef) {
            this.dialogRef.close(false);
          }

          this.dialogRef = this.dialog.open(KnkTrackKnokComponent, {
            panelClass: ['knk-overlay-pane', 'knk-overlay-pane--knok'],
            backdropClass: 'knk-overlay-backdrop',
            maxWidth: '100%',
            minWidth: '100vw',
            width: '100%',
            maxHeight: '100%',
            minHeight: '100vh',
            height: '100%',
            autoFocus: false,
            disableClose: true,
            closeOnNavigation: true,
            data: this.data
          });

          this.dialogRef.afterOpen().takeLast(1).debounceTime(10).subscribe((): void => {
            this.renderer.setStyle(this.document.documentElement, 'overflow', 'hidden');
            this.renderer.setStyle(this.document.body, 'overflow', 'hidden');
          });

          this.dialogRef.afterClosed().takeLast(1).debounceTime(10).subscribe((clean: boolean): void => {
            this.renderer.setStyle(this.document.documentElement, 'overflow', null);
            this.renderer.setStyle(this.document.body, 'overflow', null);
            if (clean || clean === undefined) {
              let url: UrlTree = this.router.createUrlTree(['.', {outlets: {'knok': null}}], {relativeTo: this.route.parent});
              this.router.navigateByUrl(url);
            }
          });
        }, 10);
      });
    });
  }
}
