#!/usr/bin/python

import RPi.GPIO as GPIO
import time
import datetime
import picamera
import os, subprocess
import sys
import socket
from thread import *


HOST = '127.0.0.1'	# Symbolic name meaning all available interfaces
PORT = 8888	        # Arbitrary non-privileged port

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
print 'Socket created'

#Bind socket to local host and port
try:
	s.bind((HOST, PORT))
except socket.error as msg:
	print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
	sys.exit()
	
print 'Socket bind complete'

#Start listening on socket
s.listen(10)
print 'Socket now listening'

#wait to accept a connection - blocking call
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])


#Function for handling connections. This will be used to create threads
def clientthread(conn):
	#Sending message to connected client
	# conn.send('Welcome to the server. Type something and hit enter\n') #send only takes string
	
	#infinite loop so that function do not terminate and thread do not end.
	while True:
		
		#Receiving from client
		data = conn.recv(1024)
		# print data
		setvalue( data ) 
		# reply = 'OK...' + data
		if not data: 
			break
		# conn.sendall(reply)
	
	#came out of loop
	print 'Connection Closed'
	conn.close()


def Sendpicturethread():
	global picturelist
	# print "Sendpicturethread started"
	while True: 
		if( len(picturelist)>0 ) :
			lock.acquire()
			bildname = picturelist.pop()
			lock.release()
			bildmess = "sudo -H -u pi /home/pi/telegram/sendpic.sh xxx_telegram_name_xxx " + bildname + " & "
			os.system( bildmess )
			time.sleep(3) # Wait to send the picture
		time.sleep(10) # wait when idle
	print "Sendpicthread ended" 

	
# Function to do something according to the message received.
def setvalue( value ):
	global securityactive, counter, exitnow, silentmode, aktivierungsnachricht, picturestaken
	print 'This is the function so set :.' + value + '...'
	
	if( value == 'Start' ): 
		securityactive = True
		print 'Start called.'

	if(value == 'Stop' ):
		securityactive = False
		print 'Stop called ' 
		
	if(value == 'Foto' ) :
		TakePicture()
		# this function takes a picture and adds the filename to the picturelist
		print 'foto called ' 
	
	time.sleep(1)
	print 'Message handled ' 





#start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.
start_new_thread(clientthread ,(conn,))
print "New thread started"

#thread to send the pictures 
start_new_thread( Sendpicturethread , () )
print "Sendpicturethread started"

# Endlosschleife
while True:

	time.sleep(0.1)
	timecounter += 1
	


print "Script stopped"
GPIO.cleanup()           # clean up GPIO on normal exit
s.close()
GPIO.output(11, GPIO.LOW)


