class DeviceLogsController < AdminBaseController
  # 设备时间日志
  # 设备在运行时，每隔一段时间会请求一次服务器，上报设备时间等信息
  def index
    if not current_user.allowed?(:view_hm_tests)
      redirect_to "/admin", alert: "你没有权限进入此页面!" and return
    end

    @q = DeviceLog.ransack(params[:q])
    order_str = params[:q][:s] rescue nil
    if order_str.nil?
      @device_logs = @q.result.order("id DESC").page(params[:page])
    else
      @device_logs = @q.result.page(params[:page])
    end
    @page_title = "设备时间日志"
  end

  def jumbotron
    if not current_user.allowed?(:view_jumbotron)
      redirect_to "/admin", alert: "你没有权限进入此页面!" and return
    end

    @page_title = "Jumbotron"
    if current_user.has_unsafe_password?
      @unsafe_password = true  # Later this should moved to a before action
    end
  end

  # 设备时间日志明细记录
  def histories
    @device_log = DeviceLog.find params[:id]
    @device_log_histories = @device_log.device_log_histories.order("id DESC").page(params[:page])
  end

  def tests
    if not current_user.allowed?(:view_hm_tests)
      redirect_to "/admin", alert: "你没有权限进入此页面!" and return
    end

    @q = DeviceTest.ransack(params[:q])
    order_str = params[:q][:s] rescue nil
    if order_str.nil?
      @device_tests = @q.result.order("id DESC").page(params[:page]).per(100)
    else
      @device_tests = @q.result.page(params[:page]).per(100)
    end
    @page_title = "潓美设备测试记录"
  end

  def test_histories
    @device_test = DeviceTest.find params[:test_id]
    @device_tese_histories = @device_test.device_test_histories.order("created_at DESC").page(params[:page])
    @aging_tests = DeviceAgingTest.where(mac: @device_test.mac.downcase).order("id DESC")
  end

  def test_history_log
    @device_test = DeviceTest.find params[:test_id]
    @device_test_history = @device_test.device_test_histories.find params[:id]
    render layout: false
  end

  def export_tests
    csv_file = File.new("/tmp/export_tests.csv", "w")
    csv_file.puts "MAC, SN, 来源IP, 首次上传时间, 最后上传时间, 错误项"
    DeviceTest.order("id DESC").each do |d|
      csv_file.puts "#{d.mac.to_s.upcase}, #{d.sn.to_s}, #{d.ip}, #{d.created_at}, #{d.updated_at}, #{d.result}"
    end
    csv_file.close
    send_file "/tmp/export_tests.csv"
  end

end
