#!/usr/bin/env python

import AT_GSM
import sys
import StringIO
import serial

class Connection(AT_GSM.Connection):
	def __init__(self, *args, **kwargs):
		AT_GSM.Connection.__init__(self, *args, **kwargs)
		response = self.execute_and_strip("AT+CMGF=?", strip_response_prefix = "+CMGF:")
		self.execute("AT+CSDH=1") # show extra fields in AT+CMGR response.
		#print response # "(0)" PDU; "(0,1)" PDU and text. will return the latter.
		assert(response.startswith("(0,1"))
		self.execute("AT+CMGF=1") # text mode.
		# AT+CPMS="ME"  # phone storage
		# AT+CPMS="SM" # SIM
		# "MT"="ME" join "SM"

	#def get_count(self):
	#	response = self.execute_and_strip("AT+CMGF=?", strip_response_prefix = "+CMGF:")
	#	count = int(response.split(",")[0])
	#	return count
		
	def get_all(self, count = 1):
		status = self.execute_and_strip('AT+CPMS="ME","ME","ME"', strip_response_prefix = "+CPMS:") # result: '"ME",176,200,"ME",176,200,"ME",176,200', that is, ID,used#,max#
		used_count, max_count = map(int, status.split(",")[1:3])
		#	rest = self.execute("AT+SSHR=0")
		# L list messages.
		# R read message.
		#rest = self.execute("AT+CMGL=%d" % count) # unsupported.
		result = []
		for index in range(1, max_count + 1):
			try:
				response = self.execute_and_strip("AT+CMGR=%d" % index, strip_response_prefix = "+CMGR:")
				result.append(response)
			except AT_GSM.CMSError, error:
				if error.code == 321: # returns "+CMS ERROR:321\x0D" if no message with that index exists.
					pass
				else:
					raise

		# TODO better use "AT+CMGL=4" in order to fetch ALL the SMS in PDU mode? # CMGL: {0=received unread messages, 1=received read messages, 2=stored unsent, 3=stored sent, 4=all}
		return result

	def PDU_get_all(self):
		# bad bad code.
		self.execute("AT+CMGF=0") # PDU mode.
		# eeek.
		#self.serial_1.write()
		for c in "AT+CMGL=4\x0D":
			self.serial_1.write(c)
		
		#self.serial_1.flush()
		while True:
			print self.serial_1.readline()
			sys.stdout.flush()
		
if __name__ == "__main__":
	SMS_connection = Connection()
	print SMS_connection.get_all()
	
	
	