class ScheduledReport < ActiveRecord::Base
  resourcify
  belongs_to :location_network
  has_many :reports
  has_and_belongs_to_many :notification_groups, join_table: :scheduled_reports_notification_groups

  def self.schedule_report
    today_date =  DateTime.now.in_time_zone(Time.zone).end_of_day - 1.day
    ScheduledReport.all.each do |r|
      created_at = r.last_generated == nil ? (r.updated_at.to_date - today_date.to_date).to_i.abs : (r.last_generated.to_date - today_date.to_date).to_i.abs
      from_time= ''
      if r.scheduled_on == 'Every Day'
        from_time = today_date.strftime("%d %b,%Y 00:00:00 UTC +00:00:00") if created_at.days >= 1.day
      elsif r.scheduled_on == 'Every Week'
        from_time = (today_date - 1.week).strftime("%d %b,%Y 00:00:00 UTC +00:00:00") if created_at.days >= 1.week
      elsif r.scheduled_on == 'Every Fortnight'
        from_time = (today_date - 2.week).strftime("%d %b,%Y 00:00:00 UTC +00:00:00") if created_at.days >= 1.fortnights
      elsif r.scheduled_on == 'Every Month'
        from_time = (today_date - 1.month).strftime("%d %b,%Y 00:00:00 UTC +00:00:00") if created_at.days == 30.days
      elsif r.scheduled_on == 'Customize' && (r.last_generated.blank? || created_at.days == 1.day)
        from_time = r.created_at
      end
      unless from_time.blank?
        report = Report.create({"title" => r.title, "location_network_id" => r.location_network_id,"from_time"=> from_time, "to_time"=> today_date,"scheduled_report_id" => r.id})
        r.update_column :last_generated,today_date
        tz = Time.now.in_time_zone(r.location_network.timezone || LocationNetwork::DEFAULT_TIMEZONE).utc_offset * 1000
        ReportWorker.perform_async(report.id,r.title, tz)
      end
    end
  end

end