# Imports needed #
import os, sys, logging
import twilio.twiml
from datetime import date
from flask import Flask, request, redirect
from twilio.rest import TwilioRestClient

# Creates named pipe variables #
pipe1_name = 'pipe1'
pipe2_name = 'pipe2'

# Enables logging to a file instead of stdout # 
# Uses the Flask app #
logging.basicConfig(filename='serv.log',level=logging.INFO)
app = Flask(__name__)

# Account information used with Twilio #
account_sid = "################################"
auth_token  = "################################"
client = TwilioRestClient(account_sid, auth_token)

# List of numbers and people to reply back with name #
callers = {
    "+18165471918": "Mitchell",
}

# Used to use HTTP GET and POST #
@app.route("/", methods=['GET', 'POST'])

# Receives SMS from user and replies back if coffee is being made or not #
def receive_sms(): 
	
	# Opens the two pipes used for reading and writing #
	pipeout = os.open(pipe1_name, os.O_WRONLY)
	pipein = open(pipe2_name, 'r')

	# Gets list of all messages that have been sent to +18164941011 #
	# and gets the last messages that was sent to it #
	messages = client.sms.messages.list(to="+18164941011")
	sentence = messages[0].body.lower()
	 
	# Print for debugging purposes #
	#print sentence
	
	# Gets the number that the message was sent from #
	from_number = request.values.get('From', None)
	
	# Checks to see if number is in the callers list shown above #
	if from_number in callers:
		# Checks to see if "coffee" is in the message #
		if ("coffee" in sentence):
		
			# Saves message saying coffee will be made #
			# Write to pipeout the from number and 1 #
			pipe_message = from_number + " 1"
			os.write(pipeout, pipe_message) 

			# Saves the message to reply to sender #
			# Reads in message form pipein #
			message = callers[from_number]
			message += pipein.readline()[:-1]
	
		# When "coffee" is not in message #
		else:
			# Write to pipeout the from number and 0 #
			pipe_message = from_number + " 0"
			os.write(pipeout, pipe_message)		
			
			# Saves the message to be replied  #
			message = "The word \"coffee\" was not detected. No coffee made."
			
	# Saves message asking how the person got the number #
	else:
		# Saves message saying number is not recognized #
		# Write to pipeout the from number and 2 #
		message = "How did you get this number?"
		pipe_message = from_number + " 2"
		os.write(pipeout, pipe_message)
 
	# Sets up a Twilio twiML response #
	# and saves the message to the response message#
	resp = twilio.twiml.Response()
	resp.message(message)
	
	# Returns the response as a string #
	return str(resp)

# Creates a named pipe if there is not one #
if not os.path.exists(pipe1_name):
    os.mkfifo(pipe1_name)

# Creates a named pipe if there is not one #
if not os.path.exists(pipe2_name):
    os.mkfifo(pipe2_name)

# Used to initiate and run in debug mode #
if __name__ == "__main__":
    app.run(debug=True)