module Dunlop::ApplicationRecordAdditions::EpochWeeks
  extend ActiveSupport::Concern

  module ClassMethods
    def set_epoch_weeks!(date_column: :date, epoch_week_column: :epoch_week)
      case ActiveRecord::Base.connection.instance_values["config"][:adapter]
      when 'sqlite3' then
        # something
        where.not(date_column => nil).update_all "#{epoch_week_column} = CAST((strftime('%J', date(#{date_column})) - 2440584.5) / 7 AS int)"
      when 'postgesql' then
        # something
        # subtract 262800 to go to first second of epoch week, divide by 604800 seconds in a week and floor
        where.not(date_column => nil).update_all "#{epoch_week_column} = FLOOR((TO_CHAR(#{date_column})::int - 2440585) / 7)"
      else
        where.not(date_column => nil).find_in_batches do |records|
          transaction do
            records.each do |record|
              record.update epoch_week_column => record.public_send(date_column).epoch_week
            end
          end
        end
      end
    end

    def set_epoch_weeks_from_iso_week!(week_column: :week, year_column: :year, epoch_week_column: :epoch_week)
      case ActiveRecord::Base.connection.instance_values["config"][:adapter]
      when 'sqlite3-disabled' then
        # something
        #update_all "#{epoch_week_column} = CAST((strftime('%J', date(#{date_column})) - 2440584.5) / 7 AS int)"
        #NOTE todo
      when 'postgesql' then
        # something
        # subtract 262800 to go to first second of epoch week, divide by 604800 seconds in a week and floor
        where.not(week_column => nil, year_column => nil).update_all "#{epoch_week_column} = FLOOR((TO_CHAR(TO_DATE(CONCAT(#{year_column}, #{week_column}), 'iyyyiw'))::int - 2440585) / 7)"
      else
        where.not(week_column => nil, year_column => nil).find_in_batches do |records|
          transaction do
            records.each do |record|
              record.update epoch_week_column => Date.commercial(record.public_send(year_column), record.public_send(week_column)).epoch_week
            end
          end
        end
      end
    end
  end
end
