import { Injectable } from '@angular/core';
import { ClinicsResponse } from './models/clinics.response';
import { ProjectsResponse } from './models/projects.response';
import { AuthenticationService } from '../authentication/authentication.service';
import { ConnectorService } from '../connector/connector.service';
import { CommonService } from '../common/common.service';
import { Observable } from 'rxjs';
import { ProjectModel } from './models/project.model';
import { ClinicModel } from './models/clinic.model';
import { OptionModel } from 'src/app/hmg-common/ui/searchable-select/option.model';

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


    public static clinics = 'Services/lists.svc/REST/GetClinicCentralized';
    public static searchByClinicId = 'Services/Doctors.svc/REST/SearchDoctorsByTime';
    public static projects = 'Services/Lists.svc/REST/GetProject';

    private static cachedClinics: ClinicsResponse;
    private static cachedClinicsOptions: OptionModel [];
    private static cachedProjects: ProjectsResponse;
    private static cachedProjectsOptions: OptionModel [];

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

    public getClinics(onError: any, errorLabel: string): Observable<ClinicsResponse> {

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

    private saveClinics(result: ClinicsResponse) {
        if (this.cs.validResponse(result)) {
            if (this.cs.hasData(result.ListClinicCentralized)) {
                ProjectsService.cachedClinics = result;
                ProjectsService.cachedClinicsOptions = this.getClinicsOptions( result.ListClinicCentralized );
            }
        }
    }



    public getProjects(onError: any, errorLabel: string): Observable<ProjectsResponse> {

        return Observable.create(observer => {
            // get from cache
            if (ProjectsService.cachedProjects) {
                observer.next(ProjectsService.cachedProjects);
                observer.complete();
            } else {
                // get from backend
                // const request = this.authService.getAuthenticatedRequest();
                const request = this.authService.getPublicRequest();

                this.con.post(ProjectsService.projects, request, onError, errorLabel).subscribe((result) => {
                    this.saveProejcts(result);
                    observer.next(result);
                    observer.complete();
                });
            }
        });
    }


    private saveProejcts(result: ProjectsResponse) {
        if (this.cs.validResponse(result)) {
            if (this.cs.hasData(result.ListProject)) {
                ProjectsService.cachedProjects = result;
                ProjectsService.cachedProjectsOptions = this.getProjectsOptions( result.ListProject);
            }
        }
    }


    public findProject(projectId: number): ProjectModel {
        if (ProjectsService.cachedProjects) {
            for (const proj of ProjectsService.cachedProjects.ListProject) {
                if (projectId === proj.ID) {
                    return proj;
                }
            }
        }
        return null;
    }

    public  cleanCache() {
        ProjectsService.cachedClinics = null;
        ProjectsService.cachedClinicsOptions = null;
        ProjectsService.cachedProjects = null;
        ProjectsService.cachedProjectsOptions = null;
    }

    private getClinicsOptions( clinics: ClinicModel []): OptionModel [] {
        const clinicsOptions = [];
        for ( const clinic of clinics ) {
            clinicsOptions.push( new OptionModel(clinic.ClinicDescription, clinic));
        }
        return clinicsOptions;
    }

    public getCachedClinicsOptions( ): OptionModel [] {
        return ProjectsService.cachedClinicsOptions ? ProjectsService.cachedClinicsOptions : [];
    }

    private getProjectsOptions( projects: ProjectModel []): OptionModel [] {
        const projectsOptions = [];
        for ( const project of projects ) {
            projectsOptions.push( new OptionModel(project.Desciption, project));
        }
        return projectsOptions;
    }
    public getCachedProjectsOptions( ): OptionModel [] {
        return ProjectsService.cachedProjectsOptions ? ProjectsService.cachedProjectsOptions : [];
    }
    
  
}

