import { Injectable } from '@angular/core';
import { AuthenticationService } from '../authentication/authentication.service';
import { ConnectorService } from '../connector/connector.service';
import { CommonService } from '../common/common.service';
import { Observable } from 'rxjs';
import { NationalitiesResponse } from './models/nationalites.response';
import { NationalityModel } from './models/nationallity.model';
import { OptionModel } from 'src/app/hmg-common/ui/searchable-select/option.model';

@Injectable({
    providedIn: 'root'
})
export class NationalityService {

    public static nationalities = 'Services/Lists.svc/REST/GetNationality';

    private static cachedNationalities: NationalitiesResponse;
    private static cachedNationalitiesOptions: OptionModel [];

    constructor(
        public authService: AuthenticationService,
        public con: ConnectorService,
        public cs: CommonService
    ) { }


    public getNationalites(onError: any, errorLabel: string): Observable<NationalitiesResponse> {

        return Observable.create(observer => {
            // get from cache
            if (NationalityService.cachedNationalities) {
                observer.next(NationalityService.cachedNationalities);
                observer.complete();
            } else {
                // get from backend
                const request = this.authService.getPublicRequest();
                this.con.post(NationalityService.nationalities, request, onError, errorLabel).subscribe((result) => {
                    this.saveNationalities(result);
                    observer.next(result);
                    observer.complete();
                });
            }
        });
    }

    private saveNationalities(result: NationalitiesResponse) {
        if (this.cs.validResponse(result)) {
            if (this.cs.hasData(result.ListNationality)) {
                NationalityService.cachedNationalities = result;
                NationalityService.cachedNationalitiesOptions = this.getNationalitesOptions( result.ListNationality );
            }
        }
    }

    public cleanCache() {
        NationalityService.cachedNationalities = null;
        NationalityService.cachedNationalitiesOptions = null;
    }

    private getNationalitesOptions( nationalites: NationalityModel []): OptionModel [] {
        const nationalitiesOptions = [];
        for ( const nationality of nationalites ) {
            nationalitiesOptions.push( new OptionModel(nationality.Name, nationality));
        }
        return nationalitiesOptions;
    }

    public getCashedNationalitesOptions(): OptionModel [] {
        if ( NationalityService.cachedNationalitiesOptions ) {
            return NationalityService.cachedNationalitiesOptions;
        } else {
            return [];
        }
    }


}
