module JamRuby
  class LessonSessionMonthlyPrice

    # calculate the price for a given month
    def self.price(lesson_booking, start_day)

      raise "lesson_booking is not monthly paid #{lesson_booking.admin_url}" if !lesson_booking.is_monthly_payment?


      data = lesson_booking.predicted_times_for_month(start_day.year, start_day.month)

      times = data[:times]
      session = data[:session]

      true_start = start_day
      if session
        # if there is already a session for the month, that is the real star
        true_start = session.scheduled_start.to_date
      end

      # filter out anything before the start day
      times.select! { |time| time.to_date >= true_start }

      result = nil
      if times.length == 0
        result = 0
      elsif times.length == 1
        result = (lesson_booking.booked_price * 0.25).round(2)
      elsif times.length == 2
        result = (lesson_booking.booked_price * 0.50).round(2)
      elsif times.length == 3
        result = (lesson_booking.booked_price * 0.75).round(2)
      else
        result = lesson_booking.booked_price
      end

      [result, times.length]
    end

    def self.adjust_for_missed_lessons(lesson_booking, price_in_cents, split)

      if !split
        split = 1.0
      end

      adjusted_price_in_cents = price_in_cents

      lesson_package_purchases = LessonPackagePurchase.where(lesson_booking: lesson_booking).where('remaining_roll_forward_amount_in_cents > 0').order(:created_at)
      remaining_roll_forward = 0
      skip_crediting = false
      reduced_amount = 0

      lesson_package_purchases.each do |lesson_package_purchase|

        if !skip_crediting

          take_off = (lesson_package_purchase.remaining_roll_forward_amount_in_cents * split).round

          amount_remaining_after_adjustment = price_in_cents - take_off

          if amount_remaining_after_adjustment <= 0
            # there isn't enough 'price_in_cents' to eat up the needed credit, so we say this teacher_distribution has no due price, and break out of the loo
            adjusted_price_in_cents = 0
            reduced_amount += price_in_cents
            lesson_package_purchase.remaining_roll_forward_amount_in_cents -= price_in_cents
            skip_crediting = true
          else
            adjusted_price_in_cents = amount_remaining_after_adjustment
            reduced_amount += take_off
            # this lesson_package_purchase is now cleared out - totally credited!
            lesson_package_purchase.remaining_roll_forward_amount_in_cents = 0
          end
        end

        remaining_roll_forward = remaining_roll_forward + lesson_package_purchase.remaining_roll_forward_amount_in_cents

        lesson_package_purchase.save!
      end

      lesson_booking.remaining_roll_forward_amount_in_cents = remaining_roll_forward
      lesson_booking.save!

      adjusted_price_in_cents
    end
  end
end

