import { AthleteModel , AthleteSettingsModel , AthleteSnapshotModel } from "../models/athlete" ; import { DatedAthleteSettingsModel } from "../models/athlete/athlete-settings" ; import * as _ from "lodash" ; /**
 * Shared by core and app to resolve AthleteModel for a given activity date
 */ export class AthleteSnapshotResolver { constructor ( athleteModel ) { this . athleteModel = ( athleteModel ) ? athleteModel : AthleteModel . DEFAULT_MODEL ; this . athleteModel . datedAthleteSettings = _ . sortBy ( this . athleteModel . datedAthleteSettings , ( model ) => { const sortOnDate = ( _ . isNull ( model . since ) ) ? new Date ( 0 ) : new Date ( model . since ) ; return sortOnDate . getTime ( ) * - 1 ; } ) ; } public athleteModel : AthleteModel ; public static getShortDateString ( onDate ) { let onDateString ; if ( onDate instanceof Date ) { const isValidDate = ! isNaN ( onDate . getTime ( ) ) ; if ( ! isValidDate ) { return null ; } onDateString = onDate . getFullYear ( ) + "-" + ( onDate . getMonth ( ) + 1 ) . toString ( ) . padStart ( 2 , "0" ) + "-" + onDate . getDate ( ) . toString ( ) . padStart ( 2 , "0" ) ; } else { if ( _ . isEmpty ( onDate ) || isNaN ( new Date ( onDate ) . getTime ( ) ) ) { return null ; } onDateString = onDate ; } return onDateString ; } param onDate returns { AthleteModel } public resolve ( onDate ) { const onDateString = AthleteSnapshotResolver . getShortDateString ( onDate ) ; let datedAthleteSettingsModel ; if ( _ . isNull ( onDateString ) ) { const foreverDatedAthleteSettings = _ . last ( this . athleteModel . datedAthleteSettings ) ; datedAthleteSettingsModel = ( foreverDatedAthleteSettings ) ? foreverDatedAthleteSettings : DatedAthleteSettingsModel . DEFAULT_MODEL ; datedAthleteSettingsModel = DatedAthleteSettingsModel . asInstance ( datedAthleteSettingsModel ) ; } else { datedAthleteSettingsModel = this . resolveDatedAthleteSettingsAtDate ( onDateString ) ; } return ( datedAthleteSettingsModel ) ? new AthleteSnapshotModel ( this . athleteModel . gender , datedAthleteSettingsModel . toAthleteSettingsModel ( ) ) : new AthleteSnapshotModel ( this . athleteModel . gender , AthleteSettingsModel . DEFAULT_MODEL ) ; } public getCurrent ( ) { return this . resolve ( ( new Date ( ) ) ) ; } public resolveDatedAthleteSettingsAtDate ( onDate ) { const onDateTime = new Date ( onDate ) . getTime ( ) ; const datedAthleteSettingsModel = _ . find ( this . athleteModel . datedAthleteSettings , ( datedAthleteSettings ) => { const fromDate = ( datedAthleteSettings . since ) ? new Date ( datedAthleteSettings . since ) : new Date ( 0 ) ; return onDateTime >= fromDate . getTime ( ) ; } ) ; return ( datedAthleteSettingsModel ) ? DatedAthleteSettingsModel . asInstance ( datedAthleteSettingsModel ) : null ; } }