# == Schema Information
#
# Table name: data_overviews
#
#  id         :integer          not null, primary key
#  item       :string(255)
#  value      :integer
#  created_at :datetime         not null
#  updated_at :datetime         not null
#  value2     :integer
#  value3     :integer
#  value4     :integer
#  value5     :integer
#
class DataOverview < ApplicationRecord

  def self.total_device_count
    Rails.cache.fetch("total_device_count", expires_in: 5.minutes) do
      DeviceLog.select("id").count
    end
  end

  def self.online_device_count
    Rails.cache.fetch("online_device_count", expires_in: 5.minutes) do
      DeviceLog.select("id").order("updated_at DESC").where("updated_at >= ?", (Time.now - 2.minutes)).count
    end
  end

  def self.device_time_histories_count
    Rails.cache.fetch("device_time_histories_count", expires_in: 30.minutes) do
      DeviceLogHistory.select("id").count rescue 0 # In dev, no table.
    end
  end

  def self.working_device_count
    where(:item => "working_device_count").first.value
  end

  def self.totoal_h2_amount
    where(:item => "totoal_h2_amount").first.value
  end

  # Execute this at end_of_day: 23:55
  # a = DeviceTest.where("result = 0 and sn != 'SA' and created_at >=? and created_at <= ?", d1, d2).select("id").count
  def self.update_test_count
    prev_day_test_pass_count = DeviceTest.where("result = 0 and sn != 'SA' and created_at >=?", Date.today.to_time).select("id").count
    prev_day_test_failed_count = DeviceTest.where("result > 0 and sn != 'SA' and created_at >=?", Date.today.to_time).select("id").count
    d = DataOverview.new(item: 'device_daily_test_stats', value: prev_day_test_pass_count, value2: prev_day_test_failed_count)
    d.save!
  end

  def self.update_demo_data # Invoke every 1 hour in cronjob
    working_device_count_record = DataOverview.where(:item => "working_device_count").first
    if working_device_count_record
      working_device_count_record.value = working_device_count_record.value + rand(-10..14)
      working_device_count_record.value = 101 if working_device_count_record.value < 100
      working_device_count_record.save
    end

    totoal_h2_amount_record = DataOverview.where(:item => "totoal_h2_amount").first
    if totoal_h2_amount_record
      totoal_h2_amount_record.value = totoal_h2_amount_record.value + rand(35..45)
      totoal_h2_amount_record.save
    end

  end

end
