import { LayoutService } from './core/layout.service';
import { Subscription, Observable } from 'rxjs';
import { Component, OnInit, OnDestroy, ViewChild } from '@angular/core';
import { Router, NavigationStart } from '@angular/router';
import { filter } from 'rxjs/operators';
import { CookieService } from 'ngx-cookie-service';
import { User } from './core/model/user.model';
import { JwtBody } from './model/jwtBody';
import { JwtUtil } from './shared/jwt.util';
import { AppState } from './store/app.reducers';
import { Store } from '@ngrx/store';
import { SetTokenAction, SignOffAction } from './auth/store/auth.actions';
import { AuthState } from './auth/store/auth.reducers';
import { ScrollEvent } from 'ngx-scroll-event';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit, OnDestroy{

  @ViewChild('sideNav') sideNav: any;

  routerSubscription: Subscription;
  navigationOpened: Boolean = false;
  authStoreSubscription: Subscription;

  updateScrollSubscription: Subscription;

  user: User = null;

  isWebView: Observable<Boolean> = this.layoutService.isWebView;

  constructor(private router: Router, private cookieService: CookieService, private layoutService: LayoutService, private appStore: Store<AppState>){
    this.updateScrollSubscription = this.layoutService.updateHasScroll.subscribe(
      () => {
        let el: any = this.sideNav.elementRef.nativeElement;
        let scrollHeight: number  = el.scrollHeight - el.clientHeight
        this.layoutService.hasScroll.next(scrollHeight > 100);
      }
    );
  }

  ngOnInit(){
    let token: string = this.cookieService.get('tadis');
    if (token.length){
      let body: JwtBody = JwtUtil.getJwtBodyFromToken(token);
      if (body !== null){
        let tokenExp: Date = new Date(body.exp * 1000);
        let now: Date = new Date();
        if (tokenExp > now){
          this.appStore.dispatch(new SetTokenAction(token));
        }
        else{
          this.appStore.dispatch(new SignOffAction());
        }
      }
    }
  
    this.authStoreSubscription = this.appStore.select('authState').subscribe(
      (state: AuthState) => {
        this.user = state.user;
      }
    );

    this.routerSubscription = this.router.events.pipe(
      filter(event => event instanceof NavigationStart)  
    ).subscribe((event) => {
      this.navigationOpened = false;
    });
  }

  onOpenedChanged(opened: Boolean){
    this.navigationOpened = opened;
  }

  ngOnDestroy(){
    this.routerSubscription.unsubscribe();
  }

  public handleScroll(event: ScrollEvent) {
    this.layoutService.isReachingBottom.next(event.isReachingBottom ? true : false);
  }
}
