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

import { AuthSelector } from '@overflow/member/store';
import { Domain } from '@overflow/commons-typescript/model/domain';
import * as ListStore from '../store/entity/noauth-probe';
import { NoAuthProbeEntitySelector } from '../store';
import { NoAuthProbe } from '@overflow/commons-typescript/model/noauth';
import { ConfirmationService } from 'primeng/primeng';
import { MessageService } from 'primeng/components/common/messageservice';

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

  constructor(
    private store: Store<ListStore.State>,
  ) {
    this.noauthProbes$ = this.store.pipe(select(NoAuthProbeEntitySelector.selectAll)).map((_noauthProbes: NoAuthProbe[]) => {
      if (null === _noauthProbes) {
        return null;
      }
      _noauthProbes.forEach(_noauthProbe => {
        _noauthProbe.descriptions = JSON.parse(_noauthProbe.description);
      });
      return _noauthProbes;
    });
  }

  ngOnInit() {
    this.store.select(AuthSelector.select('domain')).subscribe(
      (domain: Domain) => {
        this.store.dispatch(new ListStore.ReadAllByDomainID(domain.id));
      }
    );
  }

  accept(selected) {
    this.store.dispatch(new ListStore.Accept(selected));
  }

  deny(selected) {
    this.store.dispatch(new ListStore.Deny(selected));
  }
}
