require 'orf'

class Sequence
	
	attr_accessor :seq_name,:seq_fasta,:seq_qual,:orfs,:sec_desc,:fasta_length
	
	def initialize(seq_name,seq_fasta,seq_qual='')
		fasta_ori = seq_fasta.dup
		@seq_name=seq_name
		@seq_fasta = seq_fasta
		@fasta_length = fasta_ori.length
		change_degenerated_nt!
		@seq_qual = ''
		@sec_desc = ''
		@annotations=[]
		@orfs=[]
		
		@rejected=false
		@rejected_message=''
		
	end
	
	def add_orf(orf_seq, orf_t_start, orf_t_end, orf_frame, orf_stop_codon, orf_type)
		orf = Orf.new(orf_seq, orf_t_start, orf_t_end, orf_frame, orf_stop_codon, orf_type)
		@orfs.push orf
		
	end
	
	def rejected?
		return @rejected
	end
	
	def reject!(message='')
		@rejected=true
		@rejected_message=message
	end
		
	# :complete, :tmp_annotation, :error, :protein, :nucleotide, :alignment, :tcode
	def get_annotations(annotation_type)
		return @annotations.select{|a| a[:annotation_type]==annotation_type}
	end
	
	def annotate(annotation_type, message='', replace_existing = false)

		if replace_existing
			@annotations.reverse_each do |annotation| 
				if annotation[:annotation_type]==annotation_type
					@annotations.delete(annotation)
				end
			end
		end
		
		
		@annotations.push({:annotation_type=>annotation_type,:message=>message})
	end
	
	def change_degenerated_nt!
		
		
		########################################

		tranlaste_hash = {}
		tranlaste_hash['R']= [['a','g'],0]
		tranlaste_hash['W']= [['a','t'],0]
		tranlaste_hash['M']= [['a','c'],0]
		tranlaste_hash['K']= [['g','t'],0]
		tranlaste_hash['S']= [['g','c'],0]
		tranlaste_hash['Y']= [['c','t'],0]
		tranlaste_hash['H']= [['a','t','c'],0]
		tranlaste_hash['B']= [['g','t','c'],0]
		tranlaste_hash['D']= [['g','a','t'],0]
		tranlaste_hash['V']= [['g','a','c'],0]
		tranlaste_hash['N']= [['g','a','c','t'],0]

		########################################

		fix_degenerated_fasta!(tranlaste_hash)
		
		
	end
	
	def fix_degenerated_fasta!(tranlaste_hash)
		s = @seq_fasta
		res = []

		nts_of_a_line = s.split('')

		nts_of_a_line.map{
			|e|
			# puts "#{e} "

			if (e =~ /[RWMKSYHBDVN]/)

				# puts "#{e} "
				tranlaste_hash[e][1] += 1
				# puts "#{e}  #{tranlaste_hash[e][1]}"

				e = tranlaste_hash[e][0][tranlaste_hash[e][1]%tranlaste_hash[e][0].length]

				# puts "#{e}"
			end

			res.push e

		}

		@seq_fasta=res.compact.join
		# @seq_fasta='dario'
	end
  
	
end