#coding:utf-8
import sys
sys.path.append('..')
from Detection.MtcnnDetector import MtcnnDetector
from Detection.detector import Detector
from Detection.fcn_detector import FcnDetector
from train_models.mtcnn_model import P_Net, R_Net, O_Net
from prepare_data.loader import TestLoader
import cv2
import os
import numpy as np
import random
import urllib2
import requests

test_mode = "ONet"
thresh = [0.9, 0.6, 0.7]
min_face_size = 24
stride = 2
slide_window = False
shuffle = False
detectors = [None, None, None]
prefix = ['/home/mingmingzhao/MTCNN-Tensorflow/data/MTCNN_model/PNet_landmark/PNet', '/home/mingmingzhao/MTCNN-Tensorflow/data/MTCNN_model/RNet_landmark/RNet', '/home/mingmingzhao/MTCNN-Tensorflow/data/MTCNN_model/ONet_landmark/ONet']
epoch = [18, 14, 16]
batch_size = [2048, 256, 16]
model_path = ['%s-%s' % (x, y) for x, y in zip(prefix, epoch)]
# load pnet model
if slide_window:
    PNet = Detector(P_Net, 12, batch_size[0], model_path[0])
else:
    PNet = FcnDetector(P_Net, model_path[0])
detectors[0] = PNet

# load rnet model
if test_mode in ["RNet", "ONet"]:
    RNet = Detector(R_Net, 24, batch_size[1], model_path[1])
    detectors[1] = RNet

# load onet model
if test_mode == "ONet":
    ONet = Detector(O_Net, 48, batch_size[2], model_path[2])
    detectors[2] = ONet

mtcnn_detector = MtcnnDetector(detectors=detectors, min_face_size=min_face_size,
                               stride=stride, threshold=thresh, slide_window=slide_window)
gt_imdb = []
#gt_imdb.append("35_Basketball_Basketball_35_515.jpg")
#imdb_ = dict()"
#imdb_['image'] = im_path
#imdb_['label'] = 5
path = "/home/mingmingzhao/MTCNN-Tensorflow/test/lala"
for item in os.listdir(path):
    gt_imdb.append(os.path.join(path,item))
test_data = TestLoader(gt_imdb)
all_boxes,landmarks = mtcnn_detector.detect_face(test_data)
count = 0

for imagepath in gt_imdb:
    print imagepath
    image = cv2.imread(imagepath)
    for bbox in all_boxes[count]:
        cv2.putText(image,str(np.round(bbox[4],2)),(int(bbox[0]),int(bbox[1])),cv2.FONT_HERSHEY_TRIPLEX,1,color=(255,0,255))
        cv2.rectangle(image, (int(bbox[0]),int(bbox[1])),(int(bbox[2]),int(bbox[3])),(0,0,255))
        
    for landmark in landmarks[count]:
        for i in range(len(landmark)/2):
            cv2.circle(image, (int(landmark[2*i]),int(int(landmark[2*i+1]))), 3, (0,0,255))
        
    count = count + 1
    cv2.imwrite("result_landmark/%d.png" %(count),image)
    #cv2.imshow("lala",image)
    #cv2.waitKey(0)
def log2(message):
    print message

def download_img(img_remote_url,pre_log_str):
    pre_log_str+='download_img:'
    url=img_remote_url
    local_url='/data1/mingmingzhao/data_sets/test/'+url.split('/')[-1]
    log2(pre_log_str+'[remote_url:'+url+']')
    try:
        r = requests.get(url,timeout=5)
        with open(local_url, "wb") as code:
            code.write(r.content)
            log2(pre_log_str+'[ local_url:'+local_url+']')
        return local_url
    except requests.exceptions.Timeout:
        log2(pre_log_str+"5s'Timeout")
        return download_img(img_remote_url,pre_log_str)
    except requests.exceptions.RequestException as e:
        log2(pre_log_str+'resquestException')
        log2(e)
        return download_img(img_remote_url,pre_log_str)
    except requests.exceptions.TooManyRedirects:
        log2(pre_log_str+'url is bas and tyr a defferent one')
        return download_img(img_remote_url,pre_log_str)
    
def face_detc(imagepath):
    gt_imdb=[]
    img_remote_url=imagepath
    pre_log_str='face_detc:'
    #local_url=download_img(img_remote_url,pre_log_str)
    local_url=imagepath
    print local_url
    gt_imdb.append(local_url)
    test_data=TestLoader(gt_imdb)
    all_boxes1,landmarks=mtcnn_detector.detect_face(test_data)
    count=0
    boxstr=''
    #http://192.168.7.37:8393/static/jz66f1d49d97d048fe9e4a62004199d0b2_1_for_trail.jpg
   
    image = cv2.imread(local_url)
    for bbox in all_boxes1[0]:
        count+=1
        boxstr+="face[%d]:[%f,%f,%f,%f]<br/>"%(count,bbox[0],bbox[1],bbox[2],bbox[3])
        cv2.putText(image,str(np.round(bbox[4],2)),(int(bbox[0]),int(bbox[1])),cv2.FONT_HERSHEY_TRIPLEX,1,color=(255,0,255))
        cv2.rectangle(image, (int(bbox[0]),int(bbox[1])),(int(bbox[2]),int(bbox[3])),(0,0,255))
    for landmark in landmarks[0]:
        for i in range(len(landmark)/2):
            cv2.circle(image, (int(landmark[2*i]),int(int(landmark[2*i+1]))), 3, (0,0,255))
        
    write_path="/data1/mingmingzhao/data_sets/test/face_detect_%s.jpg" %(local_url.split('/')[-1])
    cv2.imwrite(write_path,image)
    process_img_path="http://192.168.7.37:8393/static/%s"%(write_path.split('/')[-1])
    return boxstr,process_img_path,count
    #cv2.imshow("lala",image)
if __name__=='__main__':
    print 'main'
'''
for data in test_data:
    print type(data)
    for bbox in all_boxes[0]:
        print bbox
        print (int(bbox[0]),int(bbox[1]))
        cv2.rectangle(data, (int(bbox[0]),int(bbox[1])),(int(bbox[2]),int(bbox[3])),(0,0,255))
    #print data
    cv2.imshow("lala",data)
    cv2.waitKey(0)
'''
