#!/usr/bin/python
# coding=utf-8
"""
Created on Tue Feb 20 21:33:57 2018

@author: veskuh
"""

import os, sys, cv2, requests, logging, re
from requests_toolbelt.multipart.encoder import MultipartEncoder

# Image file name and location
TMP_IMAGE = os.path.join(os.path.normpath(os.path.join(os.getcwd(), 'images')), 'image.jpg')
# Server URI
SERVER_URL = "tensorflow.stop.capstone.utu.fi"

# logging.basicConfig(filename = os.path.normpath(os.path.join(os.getcwd(), 'debug.log')), level = logging.DEBUG)
logging.basicConfig(filename = os.path.normpath(os.path.join(os.getcwd(), 'error.log')), level = logging.ERROR)

# Sending image to server
def sendImage(stopCode = None):
    # Send local image file to tensorflow-client
    stopCode = stopCode if stopCode else "unknown"
    try:
        with open(TMP_IMAGE, "rb") as fp:
            multipart_data = MultipartEncoder(
                fields = {
                    "stop_code": stopCode,
                    "image": (os.path.basename(TMP_IMAGE), fp, "image/jpeg")
               }
            )

            response = requests.post("http://" + SERVER_URL + "/api/v1/classifyImage/",
                data = multipart_data,
                headers = {"Content-Type": multipart_data.content_type}
            )

            if response.status_code != 200:
                raise Exception('Service unavailable')

    except Exception as err:
        logging.error('An error has occurred whilst sending the file: "{0}", for: {1}'.format(err, stopCode))

# Removing image for security purposes 
def removeImage():
    try:
        os.remove(TMP_IMAGE)
    except Exception as err:
        logging.error('An error has occurred while deleting temporary file: "{0}"'.format(err))

# Taking a picture from default webcam and saving it
def takePicture(cameraIndex):
    try:
        cap = cv2.VideoCapture(cameraIndex)
        if not cap.isOpened():
            raise Exception('Camera not available')

        ret, frame = cap.read()
        if not ret:
            raise Exception('Unable to capture image')

        cv2.imwrite(TMP_IMAGE, frame)
        cap.release()

        if not os.path.isfile(TMP_IMAGE):
            raise Exception('Saving image to disk failed')

        return True
    except Exception as err:
        logging.error('An error has occurred while capturing camera image: "{0}"'.format(err))
        return False

def main(argv):
    if argv != None and (len(argv) <= 1 or not re.match("^[\w\d_-]+$", argv[1])):
        return False

    if takePicture(0):
        sendImage(argv[1])
        removeImage()

    return True

if __name__ == "__main__":
    if not main(sys.argv):
        print("Stop identifier not provided (missing argument)")
