import { Injectable } from '@angular/core' ; import { AngularFirestore } from '@angular/fire/firestore' ; import { AngularFireFunctions } from '@angular/fire/functions' ; import * as firebase from 'firebase' ; import { Observable } from 'rxjs' ; import { map , switchMap , take , tap } from 'rxjs/operators' ; import { IMonitor , IProject , ModelFactory , MonitorModel , ProjectModel } from '@shared/models/index.model' ; import { ProjectService } from './project.service' ; /**
 * Monitor service
 */ @ Injectable ( { providedIn : 'root' , } ) export class MonitorService { param afs param fns param projectService constructor ( private afs , private fns , private projectService ) { } param projectUid param monitor public save ( projectUid , monitor ) { return this . projectService . findOneById ( projectUid ) . pipe ( take ( 1 ) , tap ( ( ) => this . pingMonitor ( projectUid , monitor . uid , 'automatic' ) ) , map ( ( project ) => { const monitors = project . monitors ; if ( monitors . find ( ( monitorModel ) => monitorModel . uid === monitor . uid ) ) { return project . monitors . map ( ( monitorModel ) => { if ( monitorModel . uid === monitor . uid ) { return new MonitorModel ( { ... monitorModel . toData ( ) , ... monitor . toData ( true ) } ) ; } return monitorModel ; } ) ; } return project . monitors . concat ( monitor ) ; } ) , switchMap ( ( monitors ) => this . afs . collection < IProject > ( 'projects' ) . doc < IProject > ( projectUid ) . set ( { monitors : ModelFactory . fromModels < MonitorModel , IMonitor > ( monitors ) , updatedOn : firebase . firestore . Timestamp . fromDate ( new Date ( ) ) , } , { merge : true } ) ) ) ; } param projectUid param monitorUid public delete ( projectUid , monitorUid ) { return this . projectService . findOneById ( projectUid ) . pipe ( take ( 1 ) , switchMap ( ( project ) => this . afs . collection < IProject > ( 'projects' ) . doc < IProject > ( projectUid ) . set ( { monitors : ModelFactory . fromModels < MonitorModel , IMonitor > ( project . monitors . filter ( ( monitorModel ) => monitorModel . uid !== monitorUid ) ) , updatedOn : firebase . firestore . Timestamp . fromDate ( new Date ( ) ) , } , { merge : true } ) ) ) ; } param projectUid param monitorUid public deletePingsByMonitor ( projectUid , monitorUid ) { const callable = this . fns . httpsCallable ( 'deletePingsByMonitor' ) ; return callable ( { projectUid , monitorUid } ) ; } param projectUid param monitorUid param type public pingMonitor ( projectUid , monitorUid , type ) { const callable = this . fns . httpsCallable ( 'pingMonitor' ) ; return callable ( { projectUid , monitorUid , type } ) ; } }