import { DataPoint } from "../DataPoint";

export class BctPageTransitionByClientPageCountry extends DataPoint {

  static source: string = 'benchmark_complete_transition'
  measurement: string = 'bct_page_transition_by_client_page_country'

  // TODO: Figure this crap out, still better in 2 places than 20
  static groups: string[] = [
    'country',
    'client_app',
    'destination'
  ]
  groups: string[] = [
    'country',
    'client_app',
    'destination'
  ]

  // TODO: Figure this crap out, still better in 2 places than 20
  static percentiles: number[] = [ 99, 95, 90, 75, 50 ]
  percentiles: number[]        = [ 99, 95, 90, 75, 50 ]

  public static query(day: string): string {
    return `
      WITH selection as (
        SELECT
          date_trunc('day', time) as day,
          time_from_fetch,
          ${this.groups.join(', ')}
        FROM "tahoe"."${this.source}"
        WHERE date = '${day}'
        AND time_from_fetch < 300000
        AND time_from_fetch >= 0
        AND time_from_fetch is not null
        AND (is_app_launch is false or destination = 'clips')
        AND (lost_visibility is false or destination = 'clips')
        AND country IS NOT null
      ),
      agged as (
        SELECT
          day,
          ${this.groups.join(', ')},
          ${this.percentiles.map(p => {
            return `percentile_cont(0.${p}) within group (order by time_from_fetch) over (partition by day, ${this.groups.join(', ')}) as duration_tp${p}`}).join(",\n")
          }
        FROM selection
      )

      select
        day,
        count(0) as count,
        ${this.groups.join(', ')},
        ${this.percentiles.map(p => { return `duration_tp${p}`}).join(', ')}
      from agged
      group by
        day,
        ${this.groups.join(', ')},
        ${this.percentiles.map(p => { return `duration_tp${p}`}).join(', ')}
      order by
        day,
        ${this.groups.join(', ')}
    `
  }

}