require 'mongoid'

class DigitalAsset
  include Mongoid::Document
  include Mongoid::Timestamps

  PROSPECTUS = '542'
  FACTSHEET = '533'
  COMMENTARY = '532'
  ANNUAL_REPORT = '529'
  SEMIANNUAL_REPORT = '541'
  SAI = '540'
  SUMMARY_PROSPECTUS = '5380'
  OTHER = ''

  field :title, type: String
  field :changed_at, type: Time
  field :audiences, type: Array, default: []
  field :sami_code, type: String
  field :product_ids, type: Array, default: []
  field :published_at, type: Time
  field :unpublished_at, type: Time
  field :expires_at, type: Time  
  field :guid, type: String
  # field :fund_ids, type: Array, default: []
  field :business_owner, type: String
  field :summary, type: String
  field :content_organization_ids, type: Array, default: []
  field :program_ids, type: Array, default: []

  field :omniture_codes, type: Array, default: []
  field :orderable, :type => Boolean, default: false
  key :guid

  # field :documents, type: Hash

  embeds_many :documents, :class_name => 'DigitalAsset::Document'

  accepts_nested_attributes_for :documents

  scope :title_is, ->(title) { where(:title => title)}
  scope :business_owner_is, ->(business_owner) { where(:business_owner => business_owner)}
  scope :guid_is, ->(guid) { where(:guid => guid)}
  # scope :funds_in, ->(fund_id) { where(:fund_ids.in => fund_id)}
  scope :audience_in, ->(audience_id) {where(:audiences.in => audience_id)}
  scope :content_organization_in, ->(content_organization_id) {where(:content_organization_ids.in => content_organization_id)}
  scope :program_id_in, ->(program_id) {where(:program_ids.in => program_id)}
  scope :sami_is, ->(sami_code) {where(:sami_code => sami_code)}
  scope :path_is, ->(path) {where(:'documents.path' => path)}
  scope :doctype_in, ->(types) {where(:'documents.content_type'.in => types)}
  scope :product_in, ->(types) {where(:product_ids.in => types)}
  scope :stale, -> {where(:updated_at.lte => 2.minutes.ago)}
  scope :orderable_is, ->(orderable) {where(:orderable => orderable)}
  scope :orderable, -> {where(orderable: true)}
  scope :has_finra, -> {where(:'documents.content_type' => '549')}
  scope :audience_in, ->(audience) {where(:audiences.in => audience)}
  # scope :order_by_fund, order_by[[:product_ids, :asc]]

  # validations
  validates_presence_of :guid, :title, :changed_at, :published_at, 
      :expires_at, :audiences, :documents

  validate :validate_future_expiration

  # validates_uniqueness_of :guid

  def self.purge!
    # last_update = DigitalAsset.desc(:updated_at).try(:first).try :updated_at
    DigitalAsset.stale.destroy_all if bulk_processed?
  end

  def validate_future_expiration
    errors.add(:expires_at, "Expiration date must be at least 1 minute from now") unless expires_at and expires_at > 1.minute.from_now
  end

  def self.bulk_processed?
    (stale.count.to_f / self.count) <= 0.05
  end

  def content_type_ids
    ids = []
    documents.try :each do |d|
      ids << d.content_type
    end
    ids
  end  

  def has_finra?
    finra_document != nil
  end

  def finra_document
    finra_docs = documents.select {|d| d.content_type == '549'}
    finra_docs.size == 1 ? finra_docs[0] : nil
  end

  def asset_type
    docs = documents.select { |d| d.content_type == PROSPECTUS || 
                                  d.content_type == SAI ||
                                  d.content_type == COMMENTARY ||
                                  d.content_type == SEMIANNUAL_REPORT ||
                                  d.content_type == ANNUAL_REPORT ||
                                  d.content_type == FACTSHEET ||
                                  d.content_type == SUMMARY_PROSPECTUS}
    docs.size == 1 ? docs[0].content_type : OTHER
  end

  def is_investor_approved?
    audiences.index('490') ? true : false
  end

  def is_institutional_use?
    audiences.index('491') ? true : false
  end

  def product
    TaxonomyTerm.label_for_term(product_ids[0])
  end
  def program 
    TaxonomyTerm.label_for_term(program_ids[0])
  end
  def content_org 
    TaxonomyTerm.label_for_term(content_organization_ids[0])
  end
  def content_type
    type_id = first_non_finra.try(:content_type)
    TaxonomyTerm.label_for_term(type_id)
  end
  def pages; first_non_finra.pages end
  
  def audience
    TaxonomyTerm.label_for_term(audiences[0])
  end

  private

  def first_non_finra; documents.detect{|d| d.content_type != '549'} end


end

class DigitalAsset::Document
  include Mongoid::Document

  field :path, type: String
  field :doc_changed_at, type: Time
  field :content_type, type: String
  field :pages, type: Integer, default: 0
  field :size, type: String
  field :mime_type, type: String

  embedded_in :digital_asset

  key :path

  validates_uniqueness_of :path

  validates_presence_of :path #, :doc_changed_at, :content_type
  validates_format_of :path, without: /\/manifest|archives\// # dont accept manifest files

end