import { Injectable } from '@angular/core';
import { Router } from '@angular/router';

import { Effect, Actions, ofType } from '@ngrx/effects';
import { Action } from '@ngrx/store';

import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';

import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/exhaustMap';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/take';

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

import { RPCService } from '@loafer/ng-rpc/service';

import {
  SigninSuccess,
  SigninCookieSuccess,
  ActionType,
} from 'packages/member/store/auth';

@Injectable()
export class Effects {

  constructor(
    private actions$: Actions,
    private rpcService: RPCService,
    private cookieService: CookieService,
  ) { }

  @Effect({ dispatch: false })
  signinSuccess$ = this.actions$
    .ofType(ActionType.SigninSuccess)
    .map((action: SigninSuccess) => action.payload)
    .do(
      (result) => {
        const authToken = result.authToken;
        // console.log(`authToken: ${authToken}`);

        const expires = new Date();
        expires.setDate(expires.getDate() + 1);
        this.cookieService.set('authToken', authToken, expires, '/');

        const queryString = `authToken=${authToken}`;

        this.rpcService.connect(queryString);
      }
    );

  @Effect({ dispatch: false })
  signinCookieSuccess$ = this.actions$
    .ofType(ActionType.SigninCookieSuccess)
    .map((action: SigninCookieSuccess) => action.payload)
    .do(
      (result) => {
        const authToken = this.cookieService.get('authToken');
        // console.log(`authToken: ${authToken}`);
        const queryString = `authToken=${authToken}`;

        this.rpcService.connect(queryString);
      }
    );
}
