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

import { Store, select } from '@ngrx/store';
import { Observable } from 'rxjs';
import { map, take } from 'rxjs/operators';
import { CookieService } from 'ngx-cookie-service';

import { AuthSelector } from '@overflow/shared/auth/store';
import * as SigninContaifnerStore from '../store/signin';

@Injectable()
export class AuthGuard implements CanActivate, CanActivateChild {
  constructor(
    private store: Store<any>,
    private router: Router,
    private cookieService: CookieService,
  ) { }

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

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

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

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

}
