class Family::Legacy::ParentTeacherDatesController < Family::Controller
  def index
    render_success :ok, json: parent_teacher_dates.map { |date|
      next if date.select_families? && !parent_teacher_families.include?(date.id) ||
        date.locked? && !family_has_meetings[date.date]

      date_props(date)
    }.compact
  end

  private
    def parent_teacher_dates
      @parent_teacher_dates ||= current_school.parent_teacher_dates
        .where('date >= ?', Time.zone.today)
        .where(active: [1, 2, 3]) # excluding closed dates
    end

    def parent_teacher_families
      @parent_teacher_families ||= current_family.parent_teacher_families.pluck(:date_id)
    end

    def parent_teacher_meetings
      @parent_teacher_meetings ||= current_school.parent_teacher_meetings
        .includes(:user)
        .where('date >= ?', Time.zone.today)
    end

    def grouped_parent_teacher_meetings
      @grouped_parent_teacher_meetings ||= parent_teacher_meetings
        .group_by { |m| [m.date, m.time.to_datetime] }
    end

    def family_has_meetings
      @family_has_meetings ||= parent_teacher_meetings
        .where(student_id: current_family.students.pluck(:id))
        .group_by(&:date)
    end

    def date_props(date)
      # Legacy uses UTC but rails auto-converts it to the set timezone so we have to do this
      utc_start = Time.zone.local_to_utc(date.start_time)
      utc_stop = Time.zone.local_to_utc(date.stop_time)
      {
        id: date.id,
        date: date.date,
        start_time: I18n.l(utc_start, format: :time),
        stop_time: I18n.l(utc_stop, format: :time),
        active: date.active,
        time_blocks: (utc_start.to_i..(utc_stop.to_i - (date.time_block + date.break_time).minute))
          .step((date.time_block + date.break_time).minute).map do |tb|
            time_block_props(date.date, tb)
          end
      }
    end

    def time_block_props(date, time_block)
      {
        time: I18n.l(Time.at(time_block).to_datetime, format: :time),
        meetings: grouped_parent_teacher_meetings[[date, Time.at(time_block).to_datetime]]
          &.map do |meeting|
            meeting_props(meeting)
          end
      }
    end

    def meeting_props(meeting)
      {
        teacher_id: meeting&.user&.id || 0, # 0 means block time for all teachers
        student_id: meeting.student_id,
        time: I18n.l(Time.zone.local_to_utc(meeting.time), format: :time)
      }
    end
end
