class Support::Sites::Schools::EdFiController < Support::Sites::Controller
  def show
    render_success :ok, json: ed_fi_props
  end

  def update
    if ed_fi_token
      if credential.update(credential_params)
        render_success :ok, message: 'Successful Ed-Fi Connection'
      else
        render_error :unprocessable_entity, errors: credential
      end
    else
      render_error :unprocessable_entity, message: 'Ed-Fi Connection Failed'
    end
  end

  def destroy
    if credential.destroy
      render_success :ok, message: 'Ed-Fi Credentials removed'
    else
      render_error :unprocessable_entity, errors: credential
    end
  end

  def test_connection
    if ed_fi_token
      render_success :ok, message: 'Successful Ed-Fi Connection'
    else
      render_error :unprocessable_entity, message: 'Ed-Fi Connection Failed'
    end
  end

  private
    def school
      @school ||= School.find_by(id: params[:school_id])
    end

    def credential
      @credential ||= EdFi::Credential.find_or_initialize_by(school: school)
    end

    def ed_fi_environment
      school.find_or_build_ed_fi_indiana_environment
    end

    def ed_fi_token
      case school.ed_fi_system
      when 'indiana'
        dir = "#{ed_fi_environment.environment_service}::ApplicationService"
        dir.constantize
          .new(school.current_year.id)
          .valid_token?(credential_params)
      when 'wisconsin'
        EdFi::Wisconsin::ApplicationService
          .new(school.current_year.id)
          .valid_token?(credential_params)
      else
        true
      end
    end

    def credential_params
      params.permit(:key, :secret)
    end

    def ed_fi_props
      {
        edfi_enabled: school.ed_fi_system?,
        key: credential.key,
        secret: credential.secret,
        state: school.ed_fi_system.titleize
      }
    end
end
