module DataTests
  module AccountingRun
    class CloudmatchCalculator
      def initialize(statement_data, vendor_contract)
        @total = statement_data["total"].to_f
        @activity_rate = get_activity_rate(statement_data["activity_rate"])
        @oms_type = vendor_contract.oms_type
        @split_rate = vendor_contract.digital_split
        @oms_fee_rate = vendor_contract.oms_fee_percentage
      end

      def calculate
        puts "  original total: #{@total}"

        gross = unrounded_gross.round(6)

        if @oms_type == :none
          unrounded_publishing = 0.0
        else
          unrounded_publishing = @total*publishing_rate
        end
        publishing = unrounded_publishing.round(6)

        oms_fees = -1*publishing*@oms_fee_rate

        if @oms_type == :both
          adjusted_gross = gross - publishing
        else
          adjusted_gross = gross
        end

        net_received = adjusted_gross*@split_rate

        if @oms_type == :label
          actual_net = net_received - publishing
        else
          actual_net = net_received
        end
        actual_net += oms_fees

        {
          "cloud_publishing" => publishing,
          "gross" => gross,
          "adjusted_gross" => adjusted_gross,
          "net_receipt" => net_received,
          "oms_fees" => oms_fees,
          "actual_net" => actual_net
        }
      end

      def unrounded_gross
        @total*@activity_rate
      end

      private

      def get_activity_rate(original_rate)
        if original_rate.nil?
          puts "  null activity_rate! defaulting to 1.0"
          1.0
        else
          puts "  activity_rate: #{original_rate}"
          original_rate.to_f
        end
      end

      def publishing_rate
        12.0/70
      end
    end
  end
end
