class Users::HeadmapsController < Users::BaseController
  def index 
    result = Gitea::User::HeadmapService.call(observed_user.login, start_stamp, end_stamp, observed_user&.gitea_token)
    @headmaps = result[2].blank? ? [] : result[2]
    headmaps_result = {}
    @headmaps.each do |entry|
      date = Time.at(entry["timestamp"]).strftime("%Y-%m-%d")
      if headmaps_result[date].nil?
        headmaps_result[date] = { "contributions" => entry["contributions"] }
      else
        headmaps_result[date]["contributions"] += entry["contributions"]
      end
    end
    @headmaps = headmaps_result
  rescue Exception => e
    uid_logger_error(e.message)
    tip_exception(e.message)
  end

  private 
  def start_stamp
    if params[:year].present?
      Date.new(params[:year].to_i, 1).to_time.to_i
    else 
      (Date.today  - 1.years).to_time.to_i  
    end
  end

  def end_stamp 
    if params[:year].present?
      (Date.new(params[:year].to_i, 1) + 1.years).to_time.end_of_day.to_i
    else 
      Date.today.to_time.end_of_day.to_i 
    end
  end
end