<commit_before># frozen_string_literal: true

class Teachers::ClassroomManagerController < ApplicationController
  include CheckboxCallback
  include CleverAuthable
  include DiagnosticReports

  respond_to :json, :html
  before_action :teacher_or_public_activity_packs, except: [:unset_preview_as_student, :unset_view_demo]
  # WARNING: these filter methods check against classroom_id, not id.
  before_action :authorize_owner!, except: [:scores, :scorebook, :lesson_planner, :preview_as_student, :unset_preview_as_student, :view_demo, :unset_view_demo, :activity_feed]
  before_action :authorize_teacher!, only: [:scores, :scorebook, :lesson_planner]
  before_action :set_alternative_schools, only: [:my_account, :update_my_account, :update_my_password]
  include ScorebookHelper
  include QuillAuthentication

  MY_ACCOUNT = 'my_account'
  ASSIGN = 'assign'

  def lesson_planner
    set_classroom_variables
  end

  def assign
    session[GOOGLE_REDIRECT] = request.env['PATH_INFO']
    session[CLEVER_REDIRECT] = request.env['PATH_INFO']
    set_classroom_variables
    set_banner_variables
    set_diagnostic_variables
    @clever_link = clever_link
    @number_of_activities_assigned = current_user.units.map(&:unit_activities).flatten.map(&:activity_id).uniq.size
    find_or_create_checkbox(Objective::EXPLORE_OUR_LIBRARY, current_user)
    if params[:tab] == 'diagnostic'
      find_or_create_checkbox(Objective::EXPLORE_OUR_DIAGNOSTICS, current_user)
    end
  end

  def generic_add_students
    redirect_to teachers_classrooms_path
  end

  # in response to ajax request
  def retrieve_classrooms_for_assigning_activities
    render json: classroom_with_students_json(current_user.classrooms_i_own)
  end

  # in response to ajax request
  def retrieve_classrooms_i_teach_for_custom_assigning_activities
    render json: classroom_with_students_json(current_user.classrooms_i_teach)
  end

  def classrooms_and_classroom_units_for_activity_share
    unit_id = params["unit_id"]
    render json: {
      classrooms: classroom_with_students_json(current_user.classrooms_i_teach),
      classroom_units: ClassroomUnit.where(unit_id: unit_id)
    }
  end

  def invite_students
    redirect_to teachers_classrooms_path
  end

  def scorebook
    @classrooms = classrooms_with_data
    if params['classroom_id']
      @classroom = @classrooms.find{|classroom| classroom["id"].to_i == params['classroom_id'].to_i}
    end
    @classrooms = @classrooms.as_json
    @classroom = @classroom.as_json
  end

  def dashboard
    if current_user.classrooms_i_teach.empty? && current_user.archived_classrooms.none? && !current_user.has_outstanding_coteacher_invitation?
      if current_user.schools_admins.any?
        redirect_to teachers_admin_dashboard_path
      end
    end
    welcome_milestone = Milestone.find_by_name(Milestone::TYPES[:see_welcome_modal])
    @must_see_modal = !UserMilestone.find_by(milestone_id: welcome_milestone&.id, user_id: current_user&.id) && Unit.unscoped.find_by_user_id(current_user&.id).nil?
    @featured_blog_posts = BlogPost.where.not(featured_order_number: nil).order(:featured_order_number)
    if @must_see_modal && current_user && welcome_milestone
      UserMilestone.find_or_create_by(user_id: current_user.id, milestone_id: welcome_milestone.id)
    end

    @objective_checklist = generate_onboarding_checklist
    @first_name = current_user.first_name

    growth_diagnostic_promotion_card_milestone = Milestone.find_by_name(Milestone::TYPES[:acknowledge_growth_diagnostic_promotion_card])
    @show_diagnostic_promotion_card = !UserMilestone.find_by(milestone_id: growth_diagnostic_promotion_card_milestone&.id, user_id: current_user&.id) && (current_user.created_at < "2021-11-29".to_date || current_user&.unit_activities&.where(activity_id: Activity.diagnostic_activity_ids)&.any?)
  end

  def students_list
    @classroom = current_user.classrooms_i_teach.find {|classroom| classroom.id == params[:id]&.to_i}
    last_name = "substring(users.name, '(?=\s).*')"
    render json: {students: @classroom&.students&.order("#{last_name} asc, users.name asc")}
  end

  def premium
    @subscription_type = current_user.premium_state
    render json: {
      hasPremium: @subscription_type,
      trial_days_remaining: current_user.trial_days_remaining,
      first_day_of_premium_or_trial: current_user.premium_updated_or_created_today?
    }
  end

  def classroom_mini
    render json: { classes: current_user.classroom_minis_info}
  end

  def dashboard_query
    @query_results = Dashboard.queries(current_user)
    render json: {
      performanceQuery: @query_results
    }
  end

  def teacher_dashboard_metrics
    json = current_user.all_classrooms_cache(key: 'classroom_manager.teacher_dashboard_metrics') do
      TeacherDashboardMetrics.new(current_user).run
    end

    render json: json
  end

  def teacher_guide
    @checkbox_data = {
      completed: current_user.checkboxes.map(&:objective_id),
      potential: Objective.all
    }
  end

  def getting_started
    @checkbox_data = current_user.getting_started_info
    render json: @checkbox_data
  end

  def scores
    cache_groups = {
      unit: params[:unit_id],
      page: params[:current_page],
      begin: params[:begin_date],
      end: params[:end_date],
      offset: current_user.utc_offset
    }

    scores = current_user.all_classrooms_cache(key: 'classroom_manager.scores', groups: cache_groups) do
       Scorebook::Query.run(params[:classroom_id], params[:current_page], params[:unit_id], params[:begin_date], params[:end_date], current_user.utc_offset)
    end

    last_page = scores.length < 200

    render json: {
      scores: scores,
      is_last_page: last_page
    }
  end

  def my_account<commit_msg>put scorebook back the way it was (#8718)<commit_after># frozen_string_literal: true

class Teachers::ClassroomManagerController < ApplicationController
  include CheckboxCallback
  include CleverAuthable
  include DiagnosticReports

  respond_to :json, :html
  before_action :teacher_or_public_activity_packs, except: [:unset_preview_as_student, :unset_view_demo]
  # WARNING: these filter methods check against classroom_id, not id.
  before_action :authorize_owner!, except: [:scores, :scorebook, :lesson_planner, :preview_as_student, :unset_preview_as_student, :view_demo, :unset_view_demo, :activity_feed]
  before_action :authorize_teacher!, only: [:scores, :scorebook, :lesson_planner]
  before_action :set_alternative_schools, only: [:my_account, :update_my_account, :update_my_password]
  include ScorebookHelper
  include QuillAuthentication

  MY_ACCOUNT = 'my_account'
  ASSIGN = 'assign'

  def lesson_planner
    set_classroom_variables
  end

  def assign
    session[GOOGLE_REDIRECT] = request.env['PATH_INFO']
    session[CLEVER_REDIRECT] = request.env['PATH_INFO']
    set_classroom_variables
    set_banner_variables
    set_diagnostic_variables
    @clever_link = clever_link
    @number_of_activities_assigned = current_user.units.map(&:unit_activities).flatten.map(&:activity_id).uniq.size
    find_or_create_checkbox(Objective::EXPLORE_OUR_LIBRARY, current_user)
    if params[:tab] == 'diagnostic'
      find_or_create_checkbox(Objective::EXPLORE_OUR_DIAGNOSTICS, current_user)
    end
  end

  def generic_add_students
    redirect_to teachers_classrooms_path
  end

  # in response to ajax request
  def retrieve_classrooms_for_assigning_activities
    render json: classroom_with_students_json(current_user.classrooms_i_own)
  end

  # in response to ajax request
  def retrieve_classrooms_i_teach_for_custom_assigning_activities
    render json: classroom_with_students_json(current_user.classrooms_i_teach)
  end

  def classrooms_and_classroom_units_for_activity_share
    unit_id = params["unit_id"]
    render json: {
      classrooms: classroom_with_students_json(current_user.classrooms_i_teach),
      classroom_units: ClassroomUnit.where(unit_id: unit_id)
    }
  end

  def invite_students
    redirect_to teachers_classrooms_path
  end

  def scorebook
    @classrooms = classrooms_with_data
    if params['classroom_id']
      @classroom = @classrooms.find{|classroom| classroom["id"].to_i == params['classroom_id'].to_i}
    end
    @classrooms = @classrooms.as_json
    @classroom = @classroom.as_json
  end

  def dashboard
    if current_user.classrooms_i_teach.empty? && current_user.archived_classrooms.none? && !current_user.has_outstanding_coteacher_invitation?
      if current_user.schools_admins.any?
        redirect_to teachers_admin_dashboard_path
      end
    end
    welcome_milestone = Milestone.find_by_name(Milestone::TYPES[:see_welcome_modal])
    @must_see_modal = !UserMilestone.find_by(milestone_id: welcome_milestone&.id, user_id: current_user&.id) && Unit.unscoped.find_by_user_id(current_user&.id).nil?
    @featured_blog_posts = BlogPost.where.not(featured_order_number: nil).order(:featured_order_number)
    if @must_see_modal && current_user && welcome_milestone
      UserMilestone.find_or_create_by(user_id: current_user.id, milestone_id: welcome_milestone.id)
    end

    @objective_checklist = generate_onboarding_checklist
    @first_name = current_user.first_name

    growth_diagnostic_promotion_card_milestone = Milestone.find_by_name(Milestone::TYPES[:acknowledge_growth_diagnostic_promotion_card])
    @show_diagnostic_promotion_card = !UserMilestone.find_by(milestone_id: growth_diagnostic_promotion_card_milestone&.id, user_id: current_user&.id) && (current_user.created_at < "2021-11-29".to_date || current_user&.unit_activities&.where(activity_id: Activity.diagnostic_activity_ids)&.any?)
  end

  def students_list
    @classroom = current_user.classrooms_i_teach.find {|classroom| classroom.id == params[:id]&.to_i}
    last_name = "substring(users.name, '(?=\s).*')"
    render json: {students: @classroom&.students&.order("#{last_name} asc, users.name asc")}
  end

  def premium
    @subscription_type = current_user.premium_state
    render json: {
      hasPremium: @subscription_type,
      trial_days_remaining: current_user.trial_days_remaining,
      first_day_of_premium_or_trial: current_user.premium_updated_or_created_today?
    }
  end

  def classroom_mini
    render json: { classes: current_user.classroom_minis_info}
  end

  def dashboard_query
    @query_results = Dashboard.queries(current_user)
    render json: {
      performanceQuery: @query_results
    }
  end

  def teacher_dashboard_metrics
    json = current_user.all_classrooms_cache(key: 'classroom_manager.teacher_dashboard_metrics') do
      TeacherDashboardMetrics.new(current_user).run
    end

    render json: json
  end

  def teacher_guide
    @checkbox_data = {
      completed: current_user.checkboxes.map(&:objective_id),
      potential: Objective.all
    }
  end

  def getting_started
    @checkbox_data = current_user.getting_started_info
    render json: @checkbox_data
  end

  def scores
    scores = Scorebook::Query.run(params[:classroom_id], params[:current_page], params[:unit_id], params[:begin_date], params[:end_date], current_user.utc_offset)

    last_page = scores.length < 200

    render json: {
      scores: scores,
      is_last_page: last_page
    }
  end

  def my_account
{'fraction_non_alphanumeric': 0.08435774095848922, 'fraction_numerical': 0.0023160520220915732, 'mean_word_length': 5.158529895776193, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '681320', 'n_tokens_mistral': 3810, 'n_tokens_neox': 3691, 'n_words': 603}