import { Injectable } from '@angular/core';
import {
  CanActivate,
  CanActivateChild,
  ActivatedRouteSnapshot,
  RouterStateSnapshot
} from '@angular/router';
import { Store } from '@ngrx/store';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/take';
import 'rxjs/add/operator/map';

import { CookieService } from 'ngx-cookie-service';

import * as AuthStore from 'packages/member/store/auth';
import { AuthSelector } from 'packages/member/store';

@Injectable()
export class AuthGuard implements CanActivate, CanActivateChild {
  constructor(
    private store: Store<AuthStore.State>,
    private cookieService: CookieService,
  ) { }

  canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
    return this.store
      .select(AuthSelector.select('signined'))
      .map(signined => {
        if (!signined) {
          if (this.cookieService.check('authToken')) {
            this.store.dispatch(new AuthStore.SigninCookie({authToken: this.cookieService.get('authToken'), returnURL: state.url}));
          } else {
            this.store.dispatch(new AuthStore.SigninRedirect(state.url));
          }
          return false;
        }

        return true;
      })
      .take(1);
  }

  canActivateChild(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
    return this.store
      .select(AuthSelector.select('signined'))
      .map(signined => {
        if (!signined) {
          this.store.dispatch(new AuthStore.SigninRedirect(state.url));
          return false;
        }

        return true;
      })
      .take(1);
  }
}
