import cv2
import commands
import re
import os
import subprocess as sp
import datetime
import CAM
import numpy as np
#-------------------------------IP & INICIALIZACION-------------------------------------------------#
RES_X = 640
RES_Y = 480

#IPoDISP = ["http://192.168.1.121/video.cgi?resolution=640x480",
 #    "http://192.168.1.122/video.cgi?resolution=640x480",
  #   "http://192.168.1.123/video.cgi?resolution=640x480"]

IPoDISP = ["http://172.16.238.36/video.cgi?resolution=640x480",
     "http://172.16.238.62/video.cgi?resolution=640x480",
     "http://172.16.238.64/video.cgi?resolution=640x480"]


#IPoDISP = ["/dev/video0","/dev/video1"]

CAMARA=[CAM.CAM()for i in IPoDISP]

for i,ip in enumerate(IPoDISP):
	CAMARA[i].init(ip)
img=[np.zeros((10,10,3)) for n in IPoDISP]



#--------------------------------TES & DIRECTORIOS-------------------------------------------------#
datehor=datetime.datetime.now()
path="Capturas_"+str(datehor.day)+"_"+str(datehor.month)+"_"+str(datehor.year)
pathlog=[]

def CreaDir(path):
	directorio=path+"-0"
	test=os.access(directorio,os.F_OK)
	if test==True:
		buscar="''ls | grep "+path+"-''"
		logs=commands.getoutput(buscar)
		logs_sep=[str(x) for x in filter(None,re.split('[\n]',logs))]
		indice=len(logs_sep)
		directorionew=path+"-"+str(indice)
		os.mkdir(directorionew,0755)
		pathlog.insert(0,directorionew)
		
	else:
		
		os.mkdir(directorio,0755)
		pathlog.insert(0,directorio)

def CreaDirIP(IPs):
	pathaux=pathlog[0]
	for s in range(IPs):
		directoriocam="/cam"+str(s)
		pathlog.insert(s,pathaux+directoriocam)
		os.mkdir(pathlog[s],0755)

CreaDir(path)
CreaDirIP(len(IPoDISP))


#---------------------------------CAPTURA---------------------------------------------------------#
print "Numero de camaras detectadas:",len(IPoDISP)
print "Ingrese el numero de tomas a realizar:"
tomas=int(raw_input())		

for i in range(tomas):
	print "Captura: "+str(i+1)
	while cv2.waitKey(10)!=27:
		for j in range(len(IPoDISP)):
			img[j]=CAMARA[j].read()
			cv2.imshow("img"+str(j),img[j])

	cv2.destroyAllWindows()
	for k in range(len(IPoDISP)):
		cv2.imwrite(pathlog[k]+"/img"+str(i)+"_"+str(k)+".jpg",img[k])


cv2.destroyAllWindows()
