import {
  AfterContentInit,
  Component,
  EventEmitter,
  Input,
  OnInit,
  Output
} from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Store, select } from '@ngrx/store';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';

import * as TotpStore from 'packages/member/store/totp';
import { AuthSelector } from 'packages/member/store';
import { TotpSelector } from 'packages/member/store';
import { Member } from '@overflow/commons-typescript/model/member';
import {RPCClientError} from '@loafer/ng-rpc/protocol';

@Component({
  selector: 'of-config-setting',
  templateUrl: './config-setting.component.html',
  styleUrls: ['./config-setting.component.scss']
})
export class ConfigSettingComponent implements OnInit, AfterContentInit {
  member: Member;
  totpState$ = this.store.pipe(select(TotpSelector.select('totp')));
  totp: any;
  totpForm: FormGroup;
  qrData: string;

  @Input()  selectedItem: any;
  @Output() close = new EventEmitter();
  @Input()  totpSettingDisplay;

  constructor(private activatedRoute: ActivatedRoute,
              private router: Router,
              private store: Store<TotpStore.State>,
              private formBuilder: FormBuilder,
              ) { }

  ngOnInit() {
    this.totpForm = this.formBuilder.group({
      'code': [
        [
        ]
      ]
    });
    this.totpState$.subscribe(
      (obj: any) => {
        console.log(obj);
        this.totp = obj;
      },
      (error: RPCClientError) => {
        console.log(error.response.message);
      }
    );
  }

  ngAfterContentInit() {

    this.store.select(AuthSelector.select('member')).subscribe(
      (member: Member) => {
        this.member = member;
        this.store.dispatch(new TotpStore.CreateTotp(this.member));
      },
      (error) => {
        console.log(error);
      }
    );

  }


  totpRegistClick() {
    const code = this.totpForm.value['code'];
    const secretCode = 'X6AWAK573M5372NM';

    this.store.select(AuthSelector.select('member')).subscribe(
      (member: Member) => {
        this.store.dispatch(new TotpStore.Regist({ member, secretCode, code }));
      },
      (error) => {
        console.log(error);
      }
    );
  }

  onCancel() {
    this.close.emit();
  }
}
