import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
import { map, mergeMap } from 'rxjs/operators';
import { DomainMemberRelationship, DomainType, PastoralDomain } from '../../entity/PastoralDomain';
import { AuthService } from '../auth.service';
import { SessionService } from '../session.service';
import { SignalRService } from '../signal-r.service';
import { CombinedKeyCrudService, CrudService } from './crud.service';
import { DomainMemberShipService } from './domain-member-ship.service';

const BASE_URL = (action: string = null) => { return `PastoralDomain${(action ? `/${action}` : '')}` }

const RELATIONSHIP_BASE_URL = (action: string = null) => { return `DomainMemberShip${(action ? `/${action}` : '')}` }
const POST_URL_ASSIGN_CELL_GROUPS = 'DomainMemberShip/AssignCellGroups'
const GET_URL_GET_CURRENT_USER_PASTORAL_DOMAIN = `PastoralDomain/GetCurrentUserPastoralDomain`;
@Injectable({
  providedIn: 'root'
})
export class PastoralDomainService extends CrudService<PastoralDomain> {

  initialized = new BehaviorSubject<boolean>(false);
  domains: PastoralDomain[] = [];
  constructor(
    protected http: HttpClient,
    private domainMemberShipService: DomainMemberShipService,
    private session: SessionService,
    private signalRService: SignalRService
  ) {
    super(http, BASE_URL);
  }
  getCurrentUserPastoralDomain() {
    return this.http.get<PastoralDomain[]>(GET_URL_GET_CURRENT_USER_PASTORAL_DOMAIN);
  }


  initialize() {
    return this.getCurrentUserPastoralDomain().pipe(map(result => {
      //this.signalRService.startSignalRConnection();
      this.domains = result;
      this.initialized.next(true);
      return result;
    }));
  }


  public get myCellGroup(): PastoralDomain {
    return this.domains.find(d => d.type == DomainType.CellGroup);
  }

  public get myHappinessGroup(): PastoralDomain {
    return this.domains.find(d => d.type == DomainType.HappinessGroup);
  }

  joinDomain(domainId: string) {

    return this.domainMemberShipService.addMemberIntoGroup(domainId, this.session.loginUserId).pipe(
      map(firstResult => { return firstResult }),
      mergeMap(
        firstResult => {
          if (firstResult) {
            return this.initialize();
          } else {
            return Observable.of(this.domains);
          }
        }));
  }
}

