class ApiLessonSessionsController < ApiController

  before_filter :api_signed_in_user
  before_filter :lookup_lesson, except: [:index, :uncollectable, :rating_decision]
  before_filter :is_teacher, only: [:accept]
  before_filter :is_student, only: []
  respond_to :json

  def index
    data = LessonSession.index(current_user, params)

    @lesson_sessions = data[:query]
    @show_teacher = true
    @next = data[:next_page]
    render "api_lesson_sessions/index", :layout => nil
  end

  def show

  end

  def analysis
    if @lesson_session.analysed
      data = @lesson_session.analysis
    else
      data = LessonSession.analysis_to_json(LessonSessionAnalyser.analyse(@lesson_session, true), true)
    end

    response = {
        analysis: data,
        status: @lesson_session.status,
        success: @lesson_session.success
    }

    render :json => response, :status => 200
  end

  def start_time
    if !current_user.admin
      response = {message: 'not admin'}
      render :json => response, :status => 422
    else
      # time = Time.zone.local_to_utc(Time.now + params[:minutes].to_i * 60)
      time = Time.current + params[:minutes].to_i * 60
      @lesson_session.music_session.scheduled_start = time
      @lesson_session.music_session.save!
      render :json => {}, :status => 200
    end
  end

  def update_unread_messages

    if params.has_key?(:teacher_unread_messages)
      @lesson_session.teacher_unread_messages = params[:teacher_unread_messages]
    end

    if params.has_key?(:student_unread_messages).present?
      @lesson_session.student_unread_messages = params[:student_unread_messages]
    end

    if !@lesson_session.save
      respond_with_model(@lesson_session)
      return
    end

  end

  def reschedule_check

    # check if within 24 hours

    if @lesson_session.is_approved?
      if params[:update_all]
        # check if the next scheduled lesson is doable
        if 15.minutes.from_now > @lesson_session.lesson_booking.next_lesson.music_session.scheduled_start
          response = {message: 'time_limit'}
          render :json => response, :status => 422
          return
        end
      else
        if 15.minutes.from_now > @lesson_session.music_session.scheduled_start
          response = {message: 'time_limit'}
          render :json => response, :status => 422
          return
        end
      end
    end

    render :json => {}, :status => 200
  end

  def cancel_check
    if @lesson_session.is_approved?
      if @lesson_session.student.id == current_user.id
        # check if within 24 hours

        if params[:update_all]
          # check if the next scheduled lesson is doable
          if 24.hours.from_now > @lesson_session.lesson_booking.next_lesson.music_session.scheduled_start
            response = {message: 'time_limit'}
            render :json => response, :status => 422
            return
          end
        else
          if 24.hours.from_now > @lesson_session.music_session.scheduled_start
            response = {message: 'time_limit'}
            render :json => response, :status => 422
            return
          end
        end
      end
    end

    render :json => {}, :status => 200
  end

  def uncollectable
    @lesson_payment_charges = current_user.uncollectables
  end

  def attach_recording

    if @lesson_session.student.id == current_user.id
      me = @lesson_session.student
      other = @lesson_session.teacher
    else
      me = @lesson_session.teacher
      other = @lesson_session.student
    end


    recordings = params[:recordings]
    recordings.each do |recording_data|
      #recording = Recording.find(recording_data[:id])
      claimed_recording = ClaimedRecording.find_by_id(recording_data[:id])
      if claimed_recording.nil? || claimed_recording.user != current_user
        raise JamPermissionError, 'only owner of claimed_recording can associated it with a lesson'
      end

      msg = ChatMessage.create(me, nil, '', ChatMessage::CHANNEL_LESSON, nil, other, @lesson_session, 'JamKazam Recording', nil, claimed_recording)
      UserMailer.lesson_attachment(me, other, @lesson_session, claimed_recording)
    end

    render :json => {}, :status => 200

  end

  def rating_decision
    if params[:as_student] == "false"
      teacher = User.find(params[:teacher_id])
      student = User.find(params[:student_id])
      lessons = teacher.lessons_with_student(student)
      rating = teacher.student_rating(student).first
    else
      teacher = User.find(params[:teacher_id])
      lessons = current_user.lessons_with_teacher(teacher)
      rating = current_user.teacher_rating(teacher.teacher).first
    end

    render :json => {lesson_count: lessons.count, rating: rating}, :status => 200


  end

  private

  def lookup_lesson
    @lesson_session = LessonSession.find(params[:id])
  end

  def is_teacher
    if @lesson_session.teacher != current_user
      raise JamPermissionError, ValidationMessages::PERMISSION_VALIDATION_ERROR
    end
  end

  def is_student
    if @lesson_session.teacher != current_user
      raise JamPermissionError, ValidationMessages::PERMISSION_VALIDATION_ERROR
    end
  end

end
