Commit d684b3bc authored by Jie Yuan's avatar Jie Yuan
Browse files

add site service

parent 020b3a9b
Loading
Loading
Loading
Loading
+12 −0
Original line number Diff line number Diff line
import { TestBed } from '@angular/core/testing';

import { SiteService } from './site.service';

describe('SiteService', () => {
  beforeEach(() => TestBed.configureTestingModule({}));

  it('should be created', () => {
    const service: SiteService = TestBed.get(SiteService);
    expect(service).toBeTruthy();
  });
});
+303 −0
Original line number Diff line number Diff line
import {EventEmitter, Injectable} from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

import {Subscription} from 'rxjs/Subscription';

import { Site } from './model/site';

import {AuthService} from './auth.service';
import {SharedService} from './shared-service';

@Injectable()
export class SiteService {



  siteList: Site[];
  siteNamesList: string[];
  /** Site that is currently shown on the site page **/
  currentSelectedSite: Site;
  currentSelectedSiteName: string;
  siteSubscription: EventEmitter<Site>;
  /** Subscription to know if the user is using another source of the sites **/
  siteSourceSubscription: EventEmitter<Site[]>;

  constructor(private httpClient: HttpClient, private authService: AuthService, private sharedService: SharedService) {
    //this.getSiteListFromGOCDB();
    //this.getSiteListFromDPMT();
    console.log('from site service constructoe')
    this.siteSubscription = new EventEmitter();
    this.siteSourceSubscription = new EventEmitter<Site[]>();
   ;
  }

  /**
   * Gets all the servers list from GOCDB
   */
  getSiteListFromGOCDB() {
    return this.getSiteListFromSource('gocdb');
  }

  /**
   * Gets all the servers list from DPMT
   */
  getSiteListFromDPMT() {
    return this.getSiteListFromSource('dpmt');
  }

  /**
   * Gets ALL the server from the backend
   * @returns {Promise<any>}
   */
  getSiteList() {
    console.log('Fetching server lists from backend');
    
    const promise = new Promise(
      (resolve, reject) => {
        /** Gets the sites from the source specified (GOCDB or DPMT) **/
        const getUrl = this.sharedService.siteURL + '/all';
        if ( sessionStorage.getItem('authHeader') !== '') {
          const headers = new HttpHeaders( sessionStorage.getItem('authHeader') ? {
           'Authorization' : sessionStorage.getItem('authHeader'),
          'Content-Type' : 'application/json'
         } : {}
         );
         this.httpClient.get<Site[]>(getUrl , {headers : headers })
         .subscribe(
           (sitesList: Site[]) => {
             this.siteList = sitesList;
             sessionStorage.setItem('JsonSiteListALL', JSON.stringify(this.siteList));
             resolve(this.siteList);
           },
           (error) => {
             reject(error);
           }
         );
        }
      });
    return promise;
  }

  getSiteListFromSource(source: String) {
    console.log('Fetching server lists from backend with source');
     

    const promise = new Promise(
      (resolve, reject) => {
      /** Gets the sites from the source specified (GOCDB or DPMT) **/
      let getUrl;
      if (source === 'all') {
        getUrl = this.sharedService.siteURL + '/all';
      } else {
        getUrl = this.sharedService.siteURL + '/' + source + '/all';
      }
      if ( sessionStorage.getItem('authHeader') !== '') {
          const headers = new HttpHeaders( true ? {
           'Authorization' : sessionStorage.getItem('authHeader'),
           'Content-Type' : 'application/json'
         } : {}
         );
         this.httpClient.get<Site[]>(getUrl , {headers : headers })
         .subscribe(
           (sitesList: Site[]) => {
             this.siteList = sitesList;
             
             resolve(this.siteList);
           },
           (error) => {
             reject(error);
           }
         );
        }
    });
    return promise;
  }
  

  getSiteNameListFromSource(source: String) {
    console.log('Fetching server name lists from backend with source');
    const promise = new Promise(
      (resolve, reject) => {
      /** Gets the sites from the source specified (GOCDB or DPMT) **/
      let getUrl;
      if (source === 'all') {
        getUrl = this.sharedService.siteURL + '/siteNames/all';
      } else {
        getUrl = this.sharedService.siteURL + '/siteNames/' + source + '/all';
      }
      if ( sessionStorage.getItem('authHeader') !== '') {
          const headers = new HttpHeaders( true ? {
           'Authorization' : sessionStorage.getItem('authHeader'),
           'Content-Type' : 'application/json'
         } : {}
         );
         this.httpClient.get<string[]>(getUrl , {headers : headers })
         .subscribe(
           (nameList: string[]) => {
             this.siteNamesList = nameList;
             const tmp = 'JsonSiteNameList' + source.toUpperCase();
             sessionStorage.setItem(tmp, JSON.stringify(this.siteNamesList));
             resolve(this.siteNamesList);
           },
           (error) => {
             reject(error);
           }
         );
        }
    });
    return promise;
  }


  setSelectedSite(newSelectedSite: Site) {
    this.currentSelectedSite = newSelectedSite;
    sessionStorage.setItem('currentSelectedSite', JSON.stringify(this.currentSelectedSite));
    this.siteSubscription.emit(newSelectedSite);
  }
 
  setSelectedSiteName(newSelectedSiteName: string) {
    const tmp = sessionStorage.getItem('currentSelectedSiteName');
    if ( newSelectedSiteName !== undefined && newSelectedSiteName !== null && newSelectedSiteName !== tmp){
      this.currentSelectedSiteName = tmp;
      sessionStorage.setItem('currentSelectedSiteName',  this.currentSelectedSiteName);
    }
  }


  

  setCurrentSelectedSiteBySiteName()  {
    if (this.currentSelectedSiteName !== null && this.currentSelectedSiteName !== undefined) {
      sessionStorage.setItem('currentSelectedSiteName', this.currentSelectedSiteName);
      this.currentSelectedSiteName = null;
    }
    const tmp = sessionStorage.getItem('currentSelectedSiteName');
    if ( tmp !== null && tmp !== '' && tmp !== undefined) {
      this.getASite(tmp).then( (asite: Site) => {
        this.currentSelectedSite = asite;
        sessionStorage.setItem('currentSelectedSite', JSON.stringify(this.currentSelectedSite));
        this.siteSubscription.emit(asite);
      }
      )
      .catch(
        errot => {
          console.log('can not get a site');
        }
      )
    }
  }

  getCurrentSelectedSite() {
    if (this.currentSelectedSite !== null && this.currentSelectedSite !== undefined) {
      sessionStorage.setItem('currentSelectedSite', JSON.stringify(this.currentSelectedSite));
      this.currentSelectedSite = null;
    }
    const tmp = sessionStorage.getItem('currentSelectedSite');
    if ( tmp !== null && tmp !== '' && tmp !== undefined) {
      return JSON.parse(tmp);
    }
  }



  /**
   * Returns true if the user can enter to the dashboard/site url
   * @returns {boolean}
   */
  canEnterToSite(): boolean {
    if (this.currentSelectedSite != null) {return true; } else {return false; }
  }

  selectSourceSite(sourceSelected: string) {

    const tmp = 'JsonSiteList' + sourceSelected.toUpperCase();
    const sessionData = sessionStorage.getItem(tmp);
    if (sessionData !== null ) {
       const list = JSON.parse(sessionData);
       this.siteSourceSubscription.emit(list);
    } else {

      switch (sourceSelected) {
        case 'all': {
          this.getSiteList()
            .then(
              (serverList: Site[]) => {
                sessionStorage.setItem('JsonSiteListALL', JSON.stringify(serverList));
                this.siteSourceSubscription.emit(serverList);
              }
            )
            .catch(
              error => {
                console.log('Error while loading sites');
              }
            );
          break;
        }
        case 'gocdb': {
          this.getSiteListFromGOCDB()
            .then(
              (serverList: Site[]) => {
                sessionStorage.setItem('JsonSiteListGOCDB', JSON.stringify(serverList));
                this.siteSourceSubscription.emit(serverList);
              }
            )
            .catch(
              error => {
                console.log('Error while loading sites');
              }
            );
          break;
        }
        case 'dpmt': {
          this.getSiteListFromDPMT()
            .then(
              (serverList: Site[]) => {
                sessionStorage.setItem('JsonSiteListDPMT', JSON.stringify(serverList));
                this.siteSourceSubscription.emit(serverList);
              }
            )
            .catch(
              error => {
                console.log('Error while loading sites');
              }
            );
          break;
        }
      }

    }
  }





  getASite(sitename: string) {
    console.log('fetch a site with its name');
    const promise = new Promise(
      (resolve, reject) => {
        /** Gets the sites from the source specified (GOCDB or DPMT) **/
        const getUrl = this.sharedService.siteURL + '/' + sitename;
        if ( sessionStorage.getItem('authHeader') !== '') {
          const headers = new HttpHeaders( sessionStorage.getItem('authHeader') ? {
           'Authorization' : sessionStorage.getItem('authHeader'),
          'Content-Type' : 'application/json'
         } : {}
         );
         this.httpClient.get<Site>(getUrl , {headers : headers })
         .subscribe(
           (asite: Site) => {
             resolve(asite);
           },
           (error) => {
             reject(error);
           }
         );
        }
      });
    return promise;

  }


}
 No newline at end of file