module JamRuby
  class JamTrackHfaRequest < ActiveRecord::Base
    include JamRuby::S3ManagerMixin


    @@log = Logging.logger[JamTrackHfaRequest]

    attr_accessible :name,  as: :admin

    validates :name,            presence: true, length: {maximum: 200}

    # look through  all jam_track requests, and find the highest one that is associated with an  approved  harry fox requests
    def self.find_max()
      max = JamTrackHfaRequestId.select('coalesce(max(request_id), 0) as max').joins('INNER JOIN jam_track_hfa_requests ON jam_track_hfa_requests.id = jam_track_hfa_request_id').where('received_at IS NOT NULL')[0]['max']
      max.to_i
    end

    def self.create(name)
      request = nil

      transaction do

        max = find_max()

        start = max + 1

        request = JamTrackHfaRequest.new
        request.name = name
        request.save!
        request.reload

        requests = []
        JamTrack.where(hfa_license_status: false).where(hfa_license_desired: true).where(alternative_license_status: false).each do |jam_track|
          request_id = JamTrackHfaRequestId.new
          request_id.jam_track = jam_track
          request_id.jam_track_hfa_request = request
          request_id.request_id = start
          start += 1
          request_id.save
          request_id.reload # to get back the request_id attribute
          requests << request_id
        end

        request_name = "JamKazam-#{request.id}-#{request.created_at.to_date.to_s}.csv"
        Dir.mktmpdir do |tmp_dir|
          out = File.join(tmp_dir, request_name)

          # Field 1 - HFA Agreement Code - Hardcode to "SSA".
          # Field 2 - Manufacturer Number - Hardcode to "M18303".
          # Field 3 - Transaction Date - Populate this field with the date that we generate this tab-delimited file, in the format YYYYMMDD - e.g. "20150813".
          # Field 4 - License Request Number - This one is slightly more involved. Basically, according to HFA we need to generate a unique numeric ID for each JamTrack license request (as opposed to each unique JamTrack, as we might need to make more than one request per JamTrack if such requests were to fail in some cases). This unique numeric ID per request should start with the number 1, and increment by 1. So I guess this feature will need to remember which of these IDs are used on each run it makes so that it knows where to start on the next run.
          # Field 7 - Total Playing Time - Minutes - We already have a JamTrack field for the duration of the JamTrack in seconds. We should keep that field, and keep using it as is. We need to use that field to populate this Field 7 and the next Field 8. So if the duration of the JamTrack in seconds were 90 seconds, then we should set Field 7 to "1" and Field 8 to "30" to signify a length of 1:30.
          # Field 8 - Total Playing Time - Seconds - See note above on Field 7.
          # Field 9 - Artist Name - Populate this field from the Artist Name field in the JamTrack record - e.g. "AC/DC".
          # Field 10 - Song Title - Populate this field from the Song Name field in the JamTrack record - e.g. "Back In Black".
          # Field 21 - Configuration Code - Hardcode to "SP".
          # Field 22 - License Type - Hardcode to "G".
          # Field 23 - Server Fixation Date - Set this to the approximate date that the JamTrack was uploaded to our servers, and format as YYYYMMDD - e.g. "20150813". I'm suggesting we update each JamTrack record with this date, just so that we have a record of this piece of data we submitted to HFA - even though HFA didn't seem at all clear about how this data is used or why it matters.
          # Field 24 - Rate Code - Hardcode to "S".
          # Field 37 - User Defined - Populate this field with our internal JamKazam unique JamTrack ID. This field value is supposed to be passed back to us from HFA in the processed output file, and we'll need this to associate the HFA License Number with our internal JamTrack ID.
          # Field 38 - Track ID - Let's also populate this field with our internal JamKazam unique JamTrack ID, just like Field 37, just for fun.


          CSV.open(out, "wb") do |csv|
            requests.each do |request|
              line = {}
              line['1'] = 'SSA'
              line['2'] = 'M18303'
              line['3'] = Time.now.to_date.strftime('%Y%m%d')
              line['4'] = request.request_id
              line['7'] = request.jam_track.duration / 60
              line['8'] = request.jam_track.duration % 60
              line['9'] = request.jam_track.original_artist
              line['10'] = request.jam_track.name
              line['21'] = 'SP'
              line['22'] = 'G'
              line['23'] = request.jam_track.server_fixation_date.strftime('%Y%m%d')
              line['24'] = 'S'
              line['37'] = request.jam_track.id
              line['38'] = request.jam_track.id

              entry = []
              38.times do |i|
                entry << line[(i + 1).to_s]
              end
              csv << entry
            end
          end

          upload_path = "harry_fox_requests/#{request_name}"
          s3_manager.upload(upload_path, out, content_type: 'text/csv')

          request.request_csv_filename = upload_path
          request.save!
        end


        request
      end
    end
  end
end

