import { Component, OnInit, OnDestroy } from '@angular/core';
import { Store, select } from '@ngrx/store';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';

import { AuthContainerSelector } from '@overflow/shared/auth/store';
import { Domain, DomainMember } from '@overflow/commons-typescript/model/domain';
import * as NoAuthProbeEntityStore from '../store/entity/noauth-probe';
import { NoAuthProbeListContainerSelector } from '../store';
import { NoAuthProbe } from '@overflow/commons-typescript/model/noauth';
import { ConfirmationService } from 'primeng/primeng';
import { MessageService } from 'primeng/components/common/messageservice';
import { RPCClientError } from '@loafer/ng-rpc';
import { Subscription } from 'rxjs';

@Component({
  selector: 'of-noauth-probe-list-container',
  templateUrl: './noauth-probe-list-container.component.html',
  providers: [ConfirmationService, MessageService]
})
export class NoAuthProbeListContainerComponent implements OnInit, OnDestroy {
  noauthProbes$: Observable<NoAuthProbe[]>;
  pending$: Observable<boolean>;
  errorSubscription: Subscription;

  constructor(
    private store: Store<any>,
    private messageService: MessageService,
  ) {
  }

  ngOnInit() {
    this.pending$ = this.store.pipe(select(NoAuthProbeListContainerSelector.selectPending));
    this.errorSubscription = this.store.pipe(select(NoAuthProbeListContainerSelector.selectError)).subscribe(
      (e: any) => {
        this.messageService.add({severity: 'error', summary: 'Service Message', detail: 'Via MessageService'});
      }
    );
    this.noauthProbes$ = this.store.pipe(select(NoAuthProbeListContainerSelector.selectAll)).map((_noauthProbes: NoAuthProbe[]) => {
      if (null === _noauthProbes) {
        return null;
      }
      _noauthProbes.forEach(_noauthProbe => {
        _noauthProbe.descriptions = JSON.parse(_noauthProbe.description);
      });
      return _noauthProbes;
    });

    this.store.select(AuthContainerSelector.selectDomainMember).subscribe(
      (domainMember: DomainMember) => {
        this.store.dispatch(new NoAuthProbeEntityStore.ReadAllByDomainID(domainMember.domain.id));
      }
    );
  }

  ngOnDestroy(): void {
    this.errorSubscription.unsubscribe();
  }

  accept(noAuthProbe: NoAuthProbe) {
    this.store.dispatch(new NoAuthProbeEntityStore.Accept({aa: noAuthProbe.id} as any));
  }

  deny(noAuthProbe: NoAuthProbe) {
    this.store.dispatch(new NoAuthProbeEntityStore.Deny(noAuthProbe.id));
  }
}
