module JamRuby
  class TeacherDistribution < ActiveRecord::Base

    belongs_to :teacher, class_name: "JamRuby::User", foreign_key: "teacher_id"
    belongs_to :teacher_payment, class_name: "JamRuby::TeacherPayment"
    belongs_to :lesson_session, class_name: "JamRuby::LessonSession"
    belongs_to :lesson_package_purchase, class_name: "JamRuby::LessonPackagePurchase"
    belongs_to :school, class_name: "JamRuby::School"
    belongs_to :retailer, class_name: "JamRuby::Retailer"

    validates :teacher, presence: true
    validates :amount_in_cents, presence: true

    def self.index(current_user, params)
      limit = params[:per_page]
      limit ||= 100
      limit = limit.to_i

      query = TeacherDistribution.where(teacher_id: current_user.id).where('school_id IS NULL').order('created_at desc')

      current_page = params[:page].nil? ? 1 : params[:page].to_i
      next_page = current_page + 1

      # will_paginate gem
      query = query.paginate(:page => current_page, :per_page => limit)

      if query.length == 0 # no more results
        {query: query, next_page: nil}
      elsif query.length < limit # no more results
        {query: query, next_page: nil}
      else
        {query: query, next_page: next_page}
      end
    end

    def not_collectable
      if is_test_drive?
        false
      elsif is_normal?
        !lesson_session.billing_should_retry
      else
        !lesson_package_purchase.billing_should_retry
      end
    end

    def self.create_for_lesson(lesson_session, for_education, split = nil, fee_rate = nil)
      distribution = create(lesson_session, for_education, split, fee_rate)
      distribution.lesson_session = lesson_session
      distribution.education = for_education

      # lock down the teacher_fee_in_cents
      distribution.teacher_fee_in_cents = distribution.calculate_teacher_fee(split, fee_rate)

      distribution
    end

    def self.create_for_lesson_package_purchase(lesson_package_purchase, for_education, split = nil, fee_rate = nil)

      distribution = create(lesson_package_purchase, for_education, split, fee_rate)
      distribution.lesson_package_purchase = lesson_package_purchase
      distribution.education = for_education

      # lock down the teacher_fee_in_cents
      distribution.teacher_fee_in_cents = distribution.calculate_teacher_fee(split, fee_rate)
      distribution.reduced_roll_forward_amount_in_cents = lesson_package_purchase.lesson_booking.adjustment_in_cents
      distribution
    end

    def self.create(target, education, split, fee_rate)
      distribution = TeacherDistribution.new
      distribution.teacher = target.teacher
      distribution.ready = false
      distribution.distributed = false
      distribution.amount_in_cents = target.lesson_booking.distribution_price_in_cents(target, education, split)
      distribution.school = target.lesson_booking.school
      distribution
    end

    def target
      if lesson_session
        lesson_session
      else
        lesson_package_purchase
      end
    end

    def amount
      amount_in_cents / 100.0
    end

    def real_distribution_in_cents
      amount_in_cents - calculate_teacher_fee
    end

    def real_distribution

      (real_distribution_in_cents / 100.0)
    end

    def real_distribution_display
      '$%.2f' % real_distribution
    end

    def jamkazam_margin_in_cents
      if is_test_drive?
        0
      else
        if school
          # if school exists, use it's rate

          # also determine if we sourced the student or not
          if target.lesson_booking.school_on_school?
            rate = school.base_rate
          else
            rate = school.jamkazam_rate + school.base_rate
          end


        else
          # otherwise use the teacher's rate
          rate = teacher.teacher.jamkazam_rate
        end
        amount_in_cents * (rate)
      end
    end

    def jamkazam_margin
      (jamkazam_margin_in_cents / 100).round(2)
    end

    def calculate_teacher_fee(split = nil, fee_rate = nil)
      if teacher_fee_in_cents
        return teacher_fee_in_cents
      else
        if education
          0
        else
          if is_test_drive?
            0
          else

            if fee_rate
              rate = (fee_rate * split) # charge_Fee is already handled elsewhere
            else
              if school
                # also determine if we sourced the student or not
                if target.lesson_booking.school_on_school?
                  rate = school.base_rate + APP_CONFIG.stripe[:charge_fee]
                else
                  rate = (school.jamkazam_rate + school.base_rate) + APP_CONFIG.stripe[:charge_fee]
                end

              else
                # otherwise use the teacher's rate
                rate = teacher.teacher.jamkazam_rate + APP_CONFIG.stripe[:charge_fee]
              end
            end

            (amount_in_cents * rate).round
          end
        end
      end

    end

    def student
      if lesson_session
        lesson_session.student
      else
        lesson_package_purchase.student
      end
    end

    def month_name
      lesson_package_purchase.month_name
    end

    def is_test_drive?
      lesson_session && lesson_session.is_test_drive?
    end

    def is_normal?
      lesson_session && !lesson_session.is_test_drive?
    end

    def is_monthly?
      !lesson_package_purchase.nil?
    end

    def description
      begin
        if lesson_session
          lesson_session.timed_description
        else
          lesson_package_purchase.timed_description
        end
      rescue
        "temp fix"
      end
    end

    def admin_url
      APP_CONFIG.admin_root_url + "/admin/teacher_distributions/" + id
    end
  end
end