module RoutinesHelper

  def routine_track(routine, current_day)
    registro = routine.history.to_s.split("|")[0, current_day]
    if current_day > registro.count
      days_extra = (current_day - registro.count)
      days_extra.times { |d| registro << "" }
    end
    return registro.map { |e| e.to_i  }
  end

  def group_category(_group, _sub_group, _category)
    if (_group == _sub_group && _category == _sub_group)
      return _group
    elsif _group == _sub_group
      return "#{_group}: #{_category}"
    else
      return "#{_group}: #{_sub_group} - #{_category}"
    end
  end

  def user_charge(history)
    vals = history.to_s.split("|")
    return "#{vals.last || 0}"
  end

  def chrone_charge(history)
    values = []
    history.to_s.split("|").each do |value|
      values << value if value != "" && value != "0"
    end
    return values.last if values.count > 0
    return "-"
  end

  def routine_realized? rutina, idx
    register = rutina.history.to_s.split("|")
    if register[idx]
      return (register[idx] || 0).to_i
    else
      return 0
    end
  end

  def routine_average(plan)
    y_labels = []
    average = []
    values = []
    plan.routines.order(number: :asc).each_with_index { |r, idx| values[idx] = routine_track(r, plan.current_day) }

    Array.new(plan.current_day).each_with_index do |day, i|
      day_avg = 0.0 # El promedio de día es calculado por el cansancio de ejercicios
      exercises_registers = 0 # los ejercicios registrados por día
      plan.routines.order(number: :asc).each_with_index do |r, idx|
        day_avg += values[idx][i]
        if values[idx][i] > 0 || i == 0
          # Sólo para días con promedio mayor a 0 quiere decir se registraron, el índice 0 es para indicar cuando comienza el plan
          exercises_registers += 1
        end
      end
      if day_avg != 0.0 || i == 0
        y_labels << l(plan.init + (i).days, format: '%d/%^b/%y')
        average << (day_avg/exercises_registers).round(2)
      end
    end
    return y_labels, average
  end

end