class ApiLessonBookingsController < ApiController

  before_filter :api_signed_in_user
  before_filter :lookup_lesson_booking, :only => [:accept, :counter, :cancel, :show]
  before_filter :auth_lesson_booking, :only => [:accept, :counter, :cancel, :show]
  respond_to :json

  def index
    data = LessonBooking.index(current_user)

    @lessons = data[:query]

    @next = data[:next_page]
    render "api_lesson_bookings/index", :layout => nil
  end

  def show

  end

  def show_choice
    @choice = TestDrivePackageChoice.find(params[:id])

    raise JamPermissionError, "You do not have permission to this data" if @choice.user != current_user
  end

  def create

    if params[:lesson_type] == LessonBooking::LESSON_TYPE_FREE
      create_free
    elsif params[:lesson_type] == LessonBooking::LESSON_TYPE_TEST_DRIVE
      create_test_drive
    elsif params[:lesson_type] == LessonBooking::LESSON_TYPE_PAID
      create_paid
    end
  end

  def create_free
    raise "not implemented"
    teacher = User.find(params[:teacher])
    specified_slots = params[:slots] || []
    slots = []
    for slot in specified_slots
      specified_slot = LessonBookingSlot.new

      if params[:recurring]
        specified_slot.slot_type = LessonBookingSlot::SLOT_TYPE_RECURRING
      else
        specified_slot.slot_type = LessonBookingSlot::SLOT_TYPE_SINGLE
      end

      day = slot[:day]
      day = Date.parse(day) if day

      specified_slot.preferred_day = day
      specified_slot.hour = slot[:hour]
      specified_slot.minute = slot[:minute]
      specified_slot.timezone = params[:timezone]
      slots << specified_slot
    end

    @lesson_booking = LessonBooking.book_free(current_user, teacher, slots, params[:description])

    if @lesson_booking.errors.any?
      recursive_errors(@lesson_booking, [:lesson_booking_slots])
    else
      render "create_free", layout: nil
    end

  end

  def create_test_drive
    teacher = User.find(params[:teacher])
    specified_slots = params[:slots] || []
    slots = []
    for slot in specified_slots
      specified_slot = LessonBookingSlot.new
      specified_slot.slot_type = LessonBookingSlot::SLOT_TYPE_SINGLE

      if slot[:date].present?
        day = slot[:date]
        day = Date.parse(day) if day
        specified_slot.preferred_day = day
      end
      specified_slot.hour = slot[:hour]
      specified_slot.minute = slot[:minute]
      specified_slot.timezone = params[:timezone]
      slots << specified_slot
    end

    @lesson_booking = LessonBooking.book_test_drive(current_user, teacher, slots, params[:description])

    if @lesson_booking.errors.any?
      recursive_errors(@lesson_booking, [:lesson_booking_slots])
    else
      render "create_test_drive", layout: nil
    end
  end

  def create_paid
    teacher = User.find(params[:teacher])
    specified_slots = params[:slots] || []
    slots = []
    for slot in specified_slots
      specified_slot = LessonBookingSlot.new
      if params[:recurring]
        specified_slot.slot_type = LessonBookingSlot::SLOT_TYPE_RECURRING
        specified_slot.day_of_week = slot[:day_of_week]
      else
        specified_slot.slot_type = LessonBookingSlot::SLOT_TYPE_SINGLE

        if slot[:date].present?
          day = slot[:date]
          day = Date.parse(day) if day && !day.include?('NaN')
          specified_slot.preferred_day = day
        end
      end


      specified_slot.hour = slot[:hour]
      specified_slot.minute = slot[:minute]
      specified_slot.timezone = params[:timezone]
      slots << specified_slot
    end

    @lesson_booking = LessonBooking.book_normal(current_user, teacher, slots, params[:description], params[:recurring], params[:payment_style], params[:lesson_length])

    if @lesson_booking.errors.any?
      recursive_errors(@lesson_booking, [:lesson_booking_slots])
    else
      render "create_paid", layout: nil
    end
  end

  def accept

    if params[:lesson_session_id]
      next_lesson = LessonSession.find(params[:lesson_session_id])
    else
      next_lesson = @lesson_booking.next_lesson
    end

    result = next_lesson.accept({
                                    message: params[:message],
                                    slot: params[:slot],
                                    accepter: current_user
                                })

    if result.errors.any?
      if result.is_a?(JamRuby::LessonBooking)
        recursive_errors(result, [:lesson_booking_slots])
      elsif result.is_a?(JamRuby::LessonSession)
        recursive_errors(result, [:lesson_booking_slots])
      else
        raise "unknown response type in accept #{result.class}"
      end
      return
    end
    @lesson_booking.reload
  end

  def counter

    if params[:lesson_session_id]
      target_lesson = LessonSession.find(params[:lesson_session_id])
    else
      target_lesson = @lesson_booking.next_lesson
    end

    @lesson_session = target_lesson

    slot = LessonBookingSlot.new
    if @lesson_booking.recurring
      if params[:update_all]
        slot.slot_type = LessonBookingSlot::SLOT_TYPE_RECURRING
      else
        slot.slot_type = LessonBookingSlot::SLOT_TYPE_SINGLE
      end
    else
      slot.slot_type = LessonBookingSlot::SLOT_TYPE_SINGLE
    end

    slot.day_of_week = params[:day_of_week]
    if params[:date].present?
      day = params[:date]
      day = Date.parse(day) if day && !day.include?('NaN')
      slot.preferred_day = day
    end
    slot.hour = params[:hour]
    slot.minute = params[:minute]
    slot.timezone = params[:timezone]
    slot.update_all = params[:update_all]

    result = target_lesson.counter({
                                       proposer: current_user,
                                       message: params[:message],
                                       slot: slot
                                   })

    if result.errors.any?
      if result.is_a?(JamRuby::LessonBooking)
        recursive_errors(result, [:lesson_booking_slots])
      elsif result.is_a?(JamRuby::LessonSession)
        recursive_errors(result, [:lesson_booking_slots])
      else
        raise "unknown response type in counter #{result.class}"
      end
      return
    end
    @lesson_booking.reload
  end

  def cancel
    if params[:lesson_session_id]
      target_lesson = LessonSession.find(params[:lesson_session_id])
    else
      target_lesson = @lesson_booking.next_lesson
    end
    @lesson_session = target_lesson

    result = target_lesson.cancel({
                                      canceler: current_user,
                                      message: params[:message],
                                      update_all: params[:update_all]
                                  })

    if result.errors.any?
      if result.is_a?(JamRuby::LessonBooking)
        recursive_errors(result, [:lesson_booking_slots])
      elsif result.is_a?(JamRuby::LessonSession)
        recursive_errors(result, [:lesson_booking_slots])
      else
        raise "unknown response type in cancel #{result.class}"
      end
      return
    end
    @lesson_booking.reload
  end

  def unprocessed
    @show_teacher = true
    @lesson_booking = LessonBooking.unprocessed(current_user).first
  end


  def unprocessed_or_intent
    @show_teacher = true
    @lesson_booking = LessonBooking.unprocessed(current_user).first
    @intent = TeacherIntent.recent_test_drive(current_user)
  end

  private
  def lookup_lesson_booking
    @lesson_booking = LessonBooking.find_by_id(params[:id])

    if @lesson_booking.nil?
      # try with lesson session
      @lesson_session = LessonSession.find_by_id(params[:id])
      if @lesson_session
        @lesson_booking = @lesson_session.lesson_booking
      end
    end
    raise ActiveRecord::RecordNotFound, "Can't find lesson booking" if @lesson_booking.nil?
  end

  def auth_lesson_booking
    if current_user.id != @lesson_booking.teacher.id && current_user.id != @lesson_booking.student.id
      raise JamPermissionError, "You do not have access to this lesson booking"
    end
  end
end
