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

export class CiicByCountry extends DataPoint {

  static source: string = 'curse_installer_install_completed'
  measurement: string = 'ciic_by_country'

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

  // 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,
          -- CASE WHEN install_completed_ms IS NULL THEN time_to_install * 1000 ELSE install_completed_ms END AS duration,
          time_to_install * 1000 AS duration,
          client_country as country
        FROM "tahoe"."${this.source}"
        WHERE date = '${day}'
        AND client_country IS NOT null
      ),
      agged as (
        SELECT
          day,
          ${this.groups.join(', ')},
          ${this.percentiles.map(p => {
            return `percentile_cont(0.${p}) within group (order by duration) over (partition by day, ${this.groups.join(', ')}) as duration_tp${p}`}).join(",\n")
          }
        FROM selection
        WHERE duration < 100000000
        AND duration >= 0
        AND duration is not null
      )

      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(', ')}
    `
  }

}