import { reactive } from 'vue'

export const store = reactive({
  cellsites: [],
  alarms: [],
  incidents: [],
  robots: [],

  // FIXME: I am replacing the entire array, should merge when can. But it's okay for demo.
  set_robots(data) { 
    this.robots = data 
  },
  set_cellsites(data) { 
    this.cellsites = data 
  },
  set_alarms(data) { 
    this.alarms = data 
  },
  set_incidents(data) { 
    this.incidents = data 
  },

  alarms_for_site(site_id) { 
    return this.alarms.filter(a => a.site_id === site_id) 
  },
  
  severity_filter: null as number | null,

  // active_tab: 'map' as 'map' | 'alarms' | 'incidents' | 'sites' | 'robots',
  // NOTE: This is to retain the state when hitting the back button and be able to handle dynamic active tabs cross-component
  detail_tabs: {},
  
  // NOTE: The below manage state for the MODES: LIVE, Historical, Frozen.
  is_frozen: false,
  frozen_at: null as number | null,
  refresh_interval_seconds: 30,
  live_countdown: 30,
  
  timeline_min: 0,
  timeline_max: Date.now(),
  timeline_position: Date.now(),

  // NOTE: this is just in case the backend breaks, we FREEZE to avoid polling infinitely.
  server_unreachable: false,

  get is_live() {
      return !this.is_frozen && this.timeline_position >= this.timeline_max - 2000 // NOTE: Buffer to deal with the flash of is_live, do not remove!
  },
  get is_historical() {
    return !this.is_live
  },
  freeze() { 
    this.is_frozen = true
    this.frozen_at = Date.now()
  },
  unfreeze() {
    this.is_frozen = false
    this.frozen_at = null
    this.server_unreachable = false
  },
  set_timeline_position(val: number) {
    this.timeline_position = val
  },
  set_refresh_interval(val: number) {
    this.refresh_interval_seconds = val
  },
})
