class StudentDocument < ApplicationRecord
  include Base::StudentDocument

  CODES = {
    TSHS: 'HS Transcript',
    TSHS5: 'HS Transcript',
    TSHS2: 'HS Transcript',
    TSMS: 'MS Transcript',
    TSEM: 'EM Transcript',
    ATTD: 'Attendance',
    GRCD: 'Report Card',
    GRCDQ1: 'Report Card',
    GRCDQ2: 'Report Card',
    GRCDQ3: 'Report Card',
    GRCDQ4: 'Report Card',
    DSCL: 'Discipline',
    MEDL: 'Medical',
    SVCL: 'Service',
    UPLD: 'Other'
  }

  belongs_to :student, foreign_key: :StudentID, inverse_of: :student_documents
  belongs_to :school_year, foreign_key: :SchoolYearID, inverse_of: :student_documents

  delegate :school, to: :student

  after_destroy :destroy_file

  scope :by_parent_viewable, ->(school) do
    attributes = {
      upload_docs: 'UPLD',
      transcript_docs: ['TSMS', 'TSEM'],
      attendance_docs: 'ATTD',
      medical_docs: 'MEDL',
      discipline_docs: 'DSCL',
      service_docs: 'SVCL'
    }
    codes = []
    school_config = school.school_config
    attributes.each do |key, value|
      codes << value if school_config.send(key)
    end

    query = where(code: codes.flatten)
    query = query.or(where('Code LIKE ?', 'GRCD%')) if school_config.report_card_docs
    query = query.or(where('Code LIKE ?', 'TSHS%')) if school_config.transcript_docs
    query
  end

  def service_url
    url = Rails.application.secrets.snap_api_url
    Pathname.new(url) + document_path
  end

  def code_label
    CODES[code[0..3].to_sym] || 'Other'
  end

  private
    def document_path
      "Schools/#{school_id}/Students/#{student_id}/#{filename}"
    end

    def file_path
      school.dir_path + document_path
    end

    def destroy_file
      FileUtils.remove_file(file_path) if File.exist?(file_path)
    end
end
