import { Component, OnInit, OnDestroy, Input, Output, EventEmitter } from '@angular/core';
import { AbstractControl, FormBuilder, FormGroup, Validators} from '@angular/forms';

import { Store } from '@ngrx/store';

import { Observable, of } from 'rxjs';
import { catchError, map, tap, take } from 'rxjs/operators';

import { Member } from '@overflow/commons-typescript/model/member';
import { DomainMember } from '@overflow/commons-typescript/model/domain';

import { AuthSelector } from '@overflow/shared/auth/store';
import * as AuthStore from '@overflow/shared/auth/store/auth';
import { MemberService } from '../service/member.service';

@Component({
  selector: 'of-member-profile',
  templateUrl: './member-profile.component.html',
})
export class MemberProfileComponent implements OnInit, OnDestroy {
  domainMember: DomainMember;
  profileForm: FormGroup;

  pending$: Observable<boolean>;
  error$: Observable<any>;

  email: AbstractControl;
  name: AbstractControl;
  phone: AbstractControl;
  company: AbstractControl;

  constructor(
    private store: Store<any>,
    private formBuilder: FormBuilder,
    private memberService: MemberService,
  ) {
  }

  ngOnInit() {
    this.store.select(AuthSelector.selectDomainMember).subscribe(
      (domainMember: DomainMember) => {
        this.domainMember = domainMember;
      }
    );
    this.initForm();
  }

  ngOnDestroy() {
  }

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

    this.email = this.profileForm.controls['email'];
    this.name = this.profileForm.controls['name'];
    this.phone = this.profileForm.controls['phone'];
    this.company = this.profileForm.controls['company'];
  }

  profileFormSubmit() {
    const formValue = Object.assign({}, this.profileForm.value);

    if (!this.checkProfile(formValue)) {
      return;
    }

    const member: Member = {
      email: formValue.email,
      name: formValue.name,
      phone: formValue.phone,
      companyName: formValue.companyName,
    };

    this.memberService.modify(member)
      .pipe(
        tap(() => {
          this.pending$ = of(true);
        }),
        map((rmember: Member) => {
          this.store.dispatch(new AuthStore.ModifySuccess(rmember));
        }),
        catchError(err => {
          this.error$ = of(err);
          return of();
        }),
        tap(() => {
          this.pending$ = of(false);
        }),
        take(1),
      ).subscribe();
  }

  private checkProfile(formValue: any): boolean {
    let isChange = false;
    if (
      formValue.email !== this.domainMember.member.email &&
      formValue.name !== this.domainMember.member.name &&
      formValue.phone !== this.domainMember.member.phone &&
      formValue.companyName !== this.domainMember.member.companyName
    ) {
      isChange = true;
    }

    return isChange;
  }
}
