require 'fuxed_lock'
require 'subtype'

configure :moc_info do |s|
  s.icons = {}
  %w{head body foot}.each {|x|
    %w{full empty}.each {|y|
      s.icons["#{x}_#{y}"] = Subtlext::Icon.new("timeline_#{x}_#{y}.xbm")
    }
  }

  s.icons[:note] = Subtlext::Icon.new("note.xbm")
  s.interval = 2
  s.bar_len = (s.config[:bar_len] || 10).to_i.abs
  s.seek = (s.config[:seek] || 5).to_i.abs
  s.data.pre = self.icons[:note].to_s
end

use SubType::Rotate

helper do
  def mocp_infos
    Hash[`mocp -i`.split(/\r?\n/).map {|l|
      p = l.split(/:/, 2).map(&:strip)
      [p[0].downcase.to_sym, p[1]]
    }]
  end

  def refresh
    infos = self.mocp_infos

    if infos[:state] == 'STOP'
      self.data.post = ''
      self.data = ' STOP'
      return
    end

    current = (self.bar_len.to_f / infos[:totalsec].to_i * infos[:currentsec].to_i).round
    left = self.bar_len - current

    post = self.icons["head_#{current > 0 ? 'full' : 'empty'}"].to_s
    (2..current).each {
      post += self.icons['body_full'].to_s
    }
    (2..left).each {
      post += self.icons['body_empty'].to_s
    }
    post += self.icons["foot_#{current == self.bar_len ? 'full' : 'empty'}"].to_s
    self.data.post = post
    self.data = (infos[:title].empty? ? infos[:file] : infos[:title]) + " "
  rescue Exception => e
    $stderr.puts e.to_s
    $stderr.puts e.backtrace
    self.data = "ERROR"
  end
end

on :run do |s|
  s.refresh
end

on :unload do |s|
  s.thread.kill
end

on :mouse_down do |s, x, y, b|
  case b
  when 1 then system("mocp -G")
  when 4 then system("mocp -k #{s.seek}")
  when 5 then system("mocp -k -#{s.seek}")
  end
#  s.refresh
end
