import {Injectable} from '@angular/core';
import {HttpClient} from "@angular/common/http";

import {CommunityInfo} from '../community/communityInfo';
import {EnvProperties} from '../../utils/properties/env-properties';
import {BehaviorSubject, Subscriber} from "rxjs";
import {map} from "rxjs/operators";

@Injectable()
export class CommunitiesService {

    public communities: BehaviorSubject<CommunityInfo[]> = null;

    constructor(private http: HttpClient) {
        this.communities = new BehaviorSubject([]);
    }
    sub;
    ngOnDestroy() {
        this.clearSubscriptions();
    }
    clearSubscriptions(){
        if (this.sub instanceof Subscriber) {
            this.sub.unsubscribe();
        }
    }
    updateCommunities(properties: EnvProperties, url: string) {
        this.sub = this.getCommunities(properties, url).subscribe(res => {
            this.communities.next(res);
        }, error => {
            this.communities.error(error);
        })
    }

    getCommunitiesState() {
        return this.communities.asObservable();
    }

    getCommunities(properties: EnvProperties, url: string) {
        return this.http.get((properties.useCache) ? (properties.cacheUrl + encodeURIComponent(url)) : url)
                        .pipe(map(res => this.parseCommunities(res)));
    }

    parseCommunities(data: any): CommunityInfo[] {
        const communities: CommunityInfo[] = [];

        const length = Array.isArray(data) ? data.length : 1;

        for (let i = 0; i < length; i++) {
            const resData = Array.isArray(data) ? data[i] : data;
            const result: CommunityInfo = new CommunityInfo();
            result['title'] = resData.name;
            result['shortTitle'] = resData.shortName;
            result['communityId'] = resData.id;
            result['queryId'] = resData.queryId;
            result['logoUrl'] = resData.logoUrl;
            result['description'] = resData.description;
            result['date'] = resData.creationDate;
            result['status'] = 'all';
            result['claim'] = resData.claim;
            result['membership'] = resData.membership;
            if (resData.hasOwnProperty('status')) {
                result['status'] = resData.status;
                result.validateStatus();
            }
            if (resData.type != null) {
                result['type'] = resData.type;
            }

            if (resData.managers != null) {
                if (result['managers'] === undefined) {
                    result['managers'] = new Array<string>();
                }

                const managers = resData.managers;
                const lengthManagers = Array.isArray(managers) ? managers.length : 1;

                for (let j = 0; j < lengthManagers; j++) {
                    const manager = Array.isArray(managers) ? managers[j] : managers;
                    result.managers[j] = manager;
                }
            }

            if (resData.subjects != null) {
                if (result['subjects'] === undefined) {
                    result['subjects'] = new Array<string>();
                }

                const subjects = resData.subjects;
                const lengthSubjects = Array.isArray(subjects) ? subjects.length : 1;

                for (let j = 0; j < lengthSubjects; j++) {
                    const subject = Array.isArray(subjects) ? subjects[i] : subjects;
                    result.subjects[j] = subject;
                }
            }
            if (result['type'] === 'community' || result['type'] === 'ri') {
                communities.push(result);
            }
        }
        return CommunityInfo.checkIsUpload(communities);
    }
}
