#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
Take a picture with the Pi Camera module and publish the path
and name of the file on a MQTT broker

@author: arofarn
"""

import picamera
import paho.mqtt.publish as mqtt
from time import sleep
from cameteo_conf import *

mqtt_client_id = "picamera"
now = datetime.utcnow()

########
# Main #
########

if not(os.path.exists(photo_dir)):
    print("Create photos directory : " + photo_dir)
    os.mkdir(photo_dir)

file_name = datetime.strftime(now, photo_name) + os.path.extsep + photo_extensions[photo_format]
file_path = os.path.join(photo_dir, file_name)

print("Shooting " + file_path)

# Taking a photo
#################

# Tell the MQTT that we start shooting
mqtt.single(camera_mqtt_topic + "/shooting" ,
            payload=    1                   ,
            qos=        1                   ,
            retain=     True                ,
            hostname=   mqtt_host           ,
            port=       mqtt_port           ,
            client_id=  mqtt_client_id      ,
            auth=       mqtt_auth           )

# Camera settings
cam = picamera.PiCamera(resolution = camera_resolution)
cam.iso             = camera_iso
cam.awb_mode        = camera_awb
cam.rotation        = camera_rotation
cam.contrast        = camera_contrast
cam.exposure_mode   = camera_expo_mode
cam.image_effect    = 'none'

#Add some EXIF tags
cam.exif_tags['EXIF.UserComment'] = 'Cameteo !'

# Warm-up
cam.start_preview()
sleep(camera_warmup_time)

cam.capture(file_path, format=photo_format, quality=95, thumbnail=None)

cam.close()

# MQTT publication
###################

mqtt_data = [{'topic':   camera_mqtt_topic + "/shooting",
              'payload': 0,
              'qos':     2,
              'retain':  True},
              {'topic':  camera_mqtt_topic + "/photos_path",
              'payload': photo_dir,
              'qos':     2,
              'retain':  True},
             {'topic':   camera_mqtt_topic + "/last_photo",
              'payload': file_name,
              'qos':     2,
              'retain':  True},
            ]

mqtt.multiple(mqtt_data,
              hostname=  mqtt_host      ,
              port=      mqtt_port      ,
              client_id= mqtt_client_id ,
              auth=      mqtt_auth      )
