import { Component, OnInit } from '@angular/core';
import { NbDialogRef } from '@nebular/theme';
import { forkJoin, Observable } from 'rxjs';
import { first, map, mergeMap } from 'rxjs/operators';
import { DropDownOption } from '../../../entity/dropDownOption';
import { FamilyMember } from '../../../entity/Member';
import { AddressInfo, DomainType, PastoralDomain } from '../../../entity/PastoralDomain';
import { LineClientService, LineMessagingAccountService } from '../../../services/crudServices/line-messaging-account.service';
import { PastoralDomainService } from '../../../services/crudServices/pastoral-domain.service';

@Component({
  selector: 'ngx-pastoral-domain-editor',
  templateUrl: './pastoral-domain-editor.component.html',
  styleUrls: ['./pastoral-domain-editor.component.scss']
})
export class PastoralDomainEditorComponent implements OnInit {
  isLoading = true;
  isAdding: boolean = false;
  processing: boolean = false;
  data: PastoralDomain;
  members: FamilyMember[];
  leaderOptions: DropDownOption[] = [new DropDownOption(null, 'N/A')];
  lineRobotOptions: DropDownOption[] = [new DropDownOption(null, 'N/A')];
  lineClientOptions: DropDownOption[] = [new DropDownOption(null, 'N/A')];
  domainTypeOptions: DropDownOption[] = [
    new DropDownOption(DomainType.CellGroup, 'Cell Group'),
    new DropDownOption(DomainType.HappinessGroup, 'Happiness Group'),
  ];

  constructor(
    private pastoralDomainService: PastoralDomainService,
    private dlgRef: NbDialogRef<PastoralDomainEditorComponent>,
    private lineAccountService: LineMessagingAccountService,
    private lineClientService: LineClientService
  ) {
  }

  ngOnInit(): void {
    this.leaderOptions = this.leaderOptions.concat(this.members.map(m => new DropDownOption(m.id, `${m.firstName} ${m.lastName}`)));
    if (this.isAdding) {
      this.data = { id: '' } as PastoralDomain;
    }

    if (!this.data.serviceAddress) {
      this.data.serviceAddress = new AddressInfo();
    }

    forkJoin(
      [this.lineAccountService.getAll(),
      this.lineClientService.getAll()]
      // getMultiValueObservable(), forkJoin on works for observables that complete
    ).pipe(first()).subscribe(result => {
      this.lineRobotOptions = this.lineRobotOptions.concat(result[0].map(m => new DropDownOption(m.id, `${m.name} (${500 - m.totalUsage})`)));
      this.lineClientOptions = this.lineClientOptions.concat(result[1].filter(l => l.isGroup).map(m => new DropDownOption(m.clientId, `${m.name}`)));
      this.isLoading = false;
    });

  }

  close() {
    this.dlgRef.close();
  }
  update() {
    if (this.processing == false) {

      this.processing = true;

      this.pastoralDomainService.createOrUpdate(this.data).pipe(first()).subscribe(result => {
        this.processing = false;

        this.dlgRef.close(true);
      });
    }
  }
}
