module JamRuby
  class RecordedTrack < ActiveRecord::Base

    self.table_name = "recorded_tracks"

    self.primary_key = 'id'

    SOUND = %w(mono stereo)
 
    belongs_to :user, :class_name => "JamRuby::User", :inverse_of => :recorded_tracks
    belongs_to :recording, :class_name => "JamRuby::Recording", :inverse_of => :recorded_tracks
    belongs_to :instrument, :class_name => "JamRuby::Instrument"

    validates :sound, :inclusion => {:in => SOUND}

    before_destroy :delete_s3_files

    # Copy an ephemeral track to create a saved one. Some fields are ok with defaults
    def self.create_from_track(track, recording)
      recorded_track = self.new
      recorded_track.recording = recording
      recorded_track.user = track.connection.user
      recorded_track.instrument = track.instrument
      recorded_track.sound = track.sound
      recorded_track.save
      recorded_track
    end

    def upload_start(length, md5)
      self.upload_id = S3Manager.multipart_upload_start(hashed_filename)
      self.length = length
      self.md5 = md5
      save
    end
    
    def upload_sign(content_md5)
      S3Manager.upload_sign(hashed_filename, content_md5, upload_id)
    end
    
    def upload_part_complete(part)
      raise JamRuby::JamArgumentError unless part == next_part_to_upload
      self.next_part_to_upload = part + 1
      save
    end
    
    def upload_complete
      S3Manager.multipart_upload_complete(upload_id)
      self.fully_uploaded = true
      save
      recording.upload_complete
    end

    def url
      S3Manager.url(hashed_filename)
    end

    def filename
      hashed_filename
    end


    # Format: "recording_#{recorded_track_id}"
    # File extension is irrelevant actually.
    def self.find_by_upload_filename(filename)
      matches = /^recording_([\w-]+)$/.match(filename)
      return nil unless matches && matches.length > 1    
      RecordedTrack.find(matches[1])
    end


    private

    def delete_s3_files
      S3Manager.delete(hashed_filename)
    end

    def hashed_filename
      S3Manager.hashed_filename('recorded_track', id)
    end

    
  end
end
