import { SpadeEventData } from "../../types/SpadeEventData";

import { InfluxTags, InfluxFields } from "../../types/influx";
import { SpadeDataPoint } from '../SpadeDataPoint';
import { continentMap, countryNameMap, regionMap } from "../../geo";

export class DesktopAppLoaded extends SpadeDataPoint {

  app_version: string;
  is_key_metric: boolean;
  is_os_startup: boolean;
  is_uac_startup: boolean;
  is_restart: boolean;
  is_new_install: boolean;
  was_updated: boolean;
  update_errored: boolean;
  valid_startup_id: boolean;
  category: string;
  subcategory: string;

  duration: number;

  constructor(fields: SpadeEventData) {
    super('desktop_app_loaded', fields);

    // Tags
    this.continent = continentMap[fields.client_country] ? continentMap[fields.client_country].continent : `Unknown Country Code: ${fields.client_country}`;
    this.country = countryNameMap[fields.client_country] ? countryNameMap[fields.client_country].name : `Unknown Country Code: ${fields.client_country}`;
    this.app_version = fields.app_version;
    this.is_key_metric = this.parseBool(fields.is_key_metric);
    this.is_os_startup = this.parseBool(fields.is_os_startup);
    this.is_uac_startup = this.parseBool(fields.is_uac_startup);
    this.is_restart = this.parseBool(fields.is_restart);
    this.is_new_install = this.parseBool(fields.is_new_install);
    this.was_updated = this.parseBool(fields.was_updated);
    this.update_errored = this.parseBool(fields.update_errored);
    this.valid_startup_id = !!fields.startup_id;
    this.category = fields.category;
    this.subcategory = fields.subcategory;

    // Fields
    this.city = fields.client_city;
    this.region = regionMap[`${fields.client_country}:${fields.client_region}`] ? regionMap[`${fields.client_country}:${fields.client_region}`].region_name : '';
    this.duration = +fields.relative_start_time;
  }

  getFields(): InfluxFields {
    return {
      ...super.getFields(),
      city: this.city,
      region: this.region,
      duration: this.duration,
    }
  }

  getTags(): InfluxTags {
    return {
      ...super.getTags(),
      continent: this.continent,
      country: this.country,
      app_version: this.app_version,
      is_key_metric: String(this.is_key_metric),
      is_os_startup: String(this.is_os_startup),
      is_uac_startup: String(this.is_uac_startup),
      is_restart: String(this.is_restart),
      is_new_install: String(this.is_new_install),
      was_updated: String(this.was_updated),
      update_errored: String(this.update_errored),
      valid_startup_id: String(this.valid_startup_id),
      category: this.category,
      subcategory: this.subcategory,
      duration_outlier: String(this.duration < 0 || this.duration > 120000)
    }
  }
}
