class WcoEmail::Context

#
# Send a single email
#

def self.notsent

def self.notsent
  where( sent_at: nil, unsubscribed_at: nil )
end

def self.scheduled

def self.scheduled
  where( :send_at.lte => Time.now  )
end

def self.summary

def self.summary
  pipeline = [
    { '$group' => {
      '_id' => { '$dateToString' => { 'format' => "%Y-%m-%d", 'date' => "$sent_at", 'timezone' => 'America/Chicago' } }, 'total' => { '$sum' => 1 }
    } },
    { '$sort' => { '_id': -1 } },
  ]
  outs = WcoEmail::Context.collection.aggregate( pipeline )
  outs.to_a
end

def body

# Looks good... 2024-01-17
def body
  if self[:body].presence
    return self[:body]
  else
    return tmpl&.body || ''
  end
end

def clear_body

def clear_body
  tmp = ActionView::Base.full_sanitizer.sanitize body
  if tmp.blank?
    self[:body] = nil
  end
end

def config

def config
  @config ||= OpenStruct.new JSON.parse( tmpl[:config_json] )
  @config
end

def from_email

def from_email
  if self[:from_email].presence
    return self[:from_email]
  elsif tmpl&.from_email
    return tmpl.from_email
  else
    return DEFAULT_FROM_EMAIL
  end
end

def get_binding

def get_binding
  @lead             = lead
  @utm_tracking_str = utm_tracking_str
  # eval( tmpl.config_exe ) ## @TODO: remove? 2024-01-17
  binding()
end

def preview_str

def preview_str
  if self[:preview_str].presence
    return self[:preview_str]
  else
    return tmpl.preview_str
  end
end

def sch; email_action; end

def sch; email_action; end

def subject

def subject
  self[:subject].presence || tmpl&.subject
end

def tmpl; email_template; end

def tmpl; email_template; end

def to_email

def to_email
  lead.email
end

def unsubscribe_url

def unsubscribe_url
  Wco::Engine.routes.url_helpers.unsubscribes_url({
    host:        Rails.application.routes.default_url_options[:host],
    lead_id:     lead_id,
    template_id: tmpl.id,
    token:       lead.unsubscribe_token,
  })
end

def utm_tracking_str

def utm_tracking_str
  {
    'cid'          => lead_id,
    'utm_campaign' => tmpl.slug,
    'utm_medium'   => 'email',
    'utm_source'   => tmpl.slug,
  }.map { |k, v| "#{k}=#{v}" }.join("&")
end