import { ActivatedRoute } from "@angular/router";
import { Observable, Subject } from "rxjs";
import { PastoralDomainService } from "../services/crudServices/pastoral-domain.service";
import { StateService } from "../services/state.service";
import { first } from 'rxjs/operators';
import { PastoralDomain } from "../entity/PastoralDomain";
import { Injectable } from "@angular/core";

@Injectable()
export abstract class MyAppBase {

    /**
     *
     */
    constructor(
        protected stateService: StateService,
        protected route: ActivatedRoute,
        protected pastoralDomainService: PastoralDomainService
    ) {
        // super(pastoralDomainService, stateService, route);
        // this.isSnapshotView = true;
    }
    isLoading: boolean = true;
    redirectIfNoDomains: boolean = true;

    pageGroupId: string;

    private domainInitialized = new Subject();;
    ngOnInit(): void {

        this.isLoading = true;
        // this.route.paramMap.subscribe((params: ParamMap) => {
        //     this.id = +params.get('id')
        // });
        this.route.paramMap.pipe(first()).subscribe(params => {
            if (params.get('groupId')) {
                this.pageGroupId = params.get('groupId');
            }

            this.pastoralDomainService.initialized.takeUntil(this.domainInitialized).subscribe(result => {
                if (result) {
                    this.domainInitialized.next();
                    if (this.redirectIfNoDomains) {
                        if (this.pageGroupId && !this.domains.find(d => d.id == this.pageGroupId)) {
                            this.pastoralDomainService.joinDomain(this.pageGroupId).pipe(first()).subscribe(result => {
                                this.pageOnInit();
                            });
                            return;
                        } else if (this.domains.length == 0) {
                            //TODO:SetUser
                            return;
                        }
                    }

                    this.pageOnInit();
                }
            });

        });
    }

    public get domains(): PastoralDomain[] {
        return this.pastoralDomainService.domains;
    }

    abstract pageOnInit(): void;

    get saveMethod(): Observable<any> {
        throw new Error("Method not implemented.");
    }

    public get happinessGroup(): PastoralDomain {
        return this.pastoralDomainService.myHappinessGroup;
    }
    public get cellGroup(): PastoralDomain {
        return this.pastoralDomainService.myCellGroup;
    }

    public get currentDomain(): PastoralDomain {
        return this.domains.find(d => d.id == this.pageGroupId);
    }
    public get currentDomainName(): string {
        if (this.domains && this.pageGroupId) {
            //let group = this.domains.find(d => d.id == this.pageGroupId);

            return this.domains.find(d => d.id == this.pageGroupId)?.name;
        }
        return "";
    }
}