import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
// import { PagesComponent } from 'app/pages/pages.component';

import * as AuthStore from '../../store/auth';
import * as ModifyStore from '../../store/modify';

import { Member } from '@overflow/commons-typescript/model/member';
import { AuthSelector } from '../../store';
import { Store, select } from '@ngrx/store';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ModifySelector } from '../../store';
import { RPCClientError } from '@loafer/ng-rpc';


@Component({
  selector: 'of-member-profile',
  templateUrl: './profile.component.html',
})
export class ProfileComponent implements OnInit, OnDestroy {

  member: Member;
  modifyForm: FormGroup;

  modifiedMember$ = this.modifyStore.pipe(select(ModifySelector.select('member')));

  constructor(
    // public app: PagesComponent,
    private activatedRoute: ActivatedRoute,
    private router: Router,
    private store: Store<AuthStore.State>,
    private formBuilder: FormBuilder,
    private modifyStore: Store<ModifyStore.State>
  ) {
  }


  ngOnInit() {
    this.store.select(AuthSelector.select('member')).subscribe(
      (member: Member) => {
        this.member = member;
      },
      (error) => {
        console.log(error);
      }
    );
    this.initForm();
  }

  ngOnDestroy() {
  }

  initForm() {
    this.modifyForm = this.formBuilder.group({
      'email': [this.member.email,
      [
        Validators.required,
        Validators.email
      ]],
      'name': [this.member.name, []],
      'companyName': [this.member.companyName, []],
      'phone': [this.member.phone, []],
    });
  }

  modifyProfile() {
    const modifyValue = Object.assign({}, this.modifyForm.value);
    const member: Member = {
      email: this.member.email,
      name: modifyValue.name,
      phone: modifyValue.phone,
      companyName: modifyValue.companyName,
    };
    this.modifyStore.dispatch(new ModifyStore.Modify(member));

    const modifiedMemberSubscription$ = this.modifiedMember$.subscribe(
      (m: Member) => {
        if (m) {
          console.log(m);
        }

        if (modifiedMemberSubscription$) {
          modifiedMemberSubscription$.unsubscribe();
        }
      },
      (error: RPCClientError) => {
        console.log(error.response.message);
      }
    );
  }

}