# Battery sublet file
# Created with sur-0.1
configure :battery do |s| # {{{
  s.interval = 60
  s.full     = 0
  s.color    = ""

  # Path
  s.now      = ""
  s.status   = ""
  
  # Find battery slot and capacity
  begin
    path = s.config[:path] || Dir["/sys/class/power_supply/B*"].first
    now  = ""
    full = ""

    if(File.exist?(File.join(path, "charge_full")))
      full = "charge_full"
      now  = "charge_now"
    elsif(File.exist?(File.join(path, "energy_full")))
      full = "energy_full"
      now  = "energy_now"
    end

    # Assemble paths
    s.now    = File.join(path, now)
    s.status = File.join(path, "status")

    # Get full capacity
    s.full = IO.readlines(File.join(path, full)).first.to_i
  rescue => err
    puts err, err.backtrace
    raise "Could't find any battery"
  end
end # }}}

on :run do |s| # {{{
  begin
    now     = IO.readlines(s.now).first.to_i
    state   = IO.readlines(s.status).first.chop
    percent = (now * 100 / s.full).to_i
    # Select icon for state
    icon = case state
      when "Charging"  
        case percent
          when 80..100 then "~[■■■■■]"
          when 60..80  then "~[■■■■ ]"
          when 40..60  then "~[■■■  ]"
          when 20..40  then "~[■■   ]"
          when 0..20   then "~[■    ]"
        end
      when "Discharging"
        case percent
          when 80..100 then "[■■■■■]"
          when 60..80  then "[■■■■ ]"
          when 40..60  then "[■■■  ]"
          when 20..40  then "[■■   ]"
          when 0..20   then "[■    ]"
        end
      when "Full"      then "[■■■■■]"
      else                  "[?????]"
    end

    color = case state
      when "Charging" then "#66d9ef"
      when "Discharging"
        case percent
          when 40..100 then "#a6e22e"
          when 20..40  then "#ffca33"
          when 10..20  then "#ff6600"
          when 0..10   then "#ff0000"
        end
      when "Full"      then "#a6e22e"
      else                  "#ffffff"
    end

    s.data = Subtlext::Color.new(color) + percent.to_s + " % " + icon
    
  rescue => err # Sanitize to prevent unloading
    s.data = "subtle"
    p err
  end
end # }}}
