#!/usr/bin/env python
# GPL. (C) 2014 Paolo Patruno.

# This program is free software; you can redistribute it and/or modify 
# it under the terms of the GNU General Public License as published by 
# the Free Software Foundation; either version 2 of the License, or 
# (at your option) any later version. 
# 
# This program is distributed in the hope that it will be useful, 
# but WITHOUT ANY WARRANTY; without even the implied warranty of 
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
# GNU General Public License for more details. 
# 
# You should have received a copy of the GNU General Public License 
# along with this program; if not, write to the Free Software 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA 
# 

from rmap import daemon
import pika
import rmap.settings

user=rmap.settings.amqpuser
password=rmap.settings.amqppassword
host="localhost"
exchange=rmap.settings.exchangecomposereportd
routing_key="composereportd"


tloop=60*3

composereportd = daemon.Daemon(
        stdin="/dev/null",
        stdout=rmap.settings.logfilecomposereportd,
        stderr=rmap.settings.errfilecomposereportd,
        pidfile=rmap.settings.lockfilecomposereportd,
        user=rmap.settings.usercomposereportd,
        group=rmap.settings.groupcomposereportd
)

def main(self):

    import subprocess,os,time
    import tempfile,datetime

    #    my_env = os.environ
    #    my_env["PYTHONPATH"] = "/usr/local/lib/python2.7/site-packages" + my_env.get("PYTHONPATH","")

    nexttime=(datetime.datetime.utcnow()+datetime.timedelta(seconds=tloop)).replace(second=0)
    waitsec=min((nexttime - datetime.datetime.utcnow()).seconds,tloop)
    print "wait for:",waitsec
    time.sleep(waitsec)

    while True:
    
        starttime=nexttime - datetime.timedelta(seconds=(tloop+tloop/3))
        print "start/end time: ",starttime.replace(microsecond=0).isoformat(' '),nexttime.replace(microsecond=0).isoformat(' ')

        try:
            #(fd, filename) = tempfile.mkstemp()
            filename="-"

            #        print ["v7d_transform","--input-format=dba","--output-format=BUFR","--network-list=rmap",
            #               "--start-date",starttime.replace(microsecond=0).isoformat(' ') ,
            #               "--end-date",nexttime.replace(microsecond=0).isoformat(' '),
            #               "--comp-start",starttime.replace(microsecond=0).isoformat(' ') ,
            #               "--comp-step","0000000000 00:01:00.000","--comp-frac-valid",".002",
            #               "--comp-stat-proc=254:0","--set-network","generic","rmap/rmap@rmap",
            #               filename]

            #compute 60s mean with max intervall = 20s as instantaneous values
            self.procs=[subprocess.Popen(["v7d_transform","--input-format=dba","--output-format=BUFR","--network-list=rmap",
                                          "--start-date",starttime.replace(microsecond=0).isoformat(' ') ,
                                          "--end-date",nexttime.replace(microsecond=0).isoformat(' '),
                                          "--comp-start",starttime.replace(microsecond=0).isoformat(' ') ,
                                          "--comp-step","0000000000 00:01:00.000","--comp-frac-valid",".002",
                                          "--comp-stat-proc=254:0","--set-network","generic","rmap/rmap@rmap",
                                          filename],stdout=subprocess.PIPE,stderr=subprocess.PIPE)]
                                          #,env=my_env


            body,outerr=self.procs[0].communicate()

            status=self.procs[0].wait()
            if status != 0:
                print "There were some errors executing v7d_transform: ",status,outerr

        except:
            print "There were some errors executing dba_transform"
            raise

        try:
            # Legge un file.
            #in_file = open(filename,"r")
            #in_file = os.fdopen(fd, "r")
            #body = in_file.read()
            #in_file.close()
            
            credentials=pika.PlainCredentials(user, password)
            properties=pika.BasicProperties(
                user_id= user,
                delivery_mode = 2, # persistent
            )

            # connection_attempts (int) - Maximum number of retry attempts
            # retry_delay (int|float) - Time to wait in seconds, before the next
            # socket_timeout (int|float) - Use for high latency networks

            connection = pika.BlockingConnection(pika.ConnectionParameters(
                host=host,credentials=credentials,
                connection_attempts=3,
                retry_delay=5,
                socket_timeout=3.))

            channel = connection.channel()
        
            #channel.queue_declare(queue=queue)

            # Turn on delivery confirmations
            channel.confirm_delivery()

            if channel.basic_publish(exchange=exchange,
                                  routing_key=routing_key,
                                  body=body,
                                  properties=properties):
                print 'Message publish was confirmed'
            else:
                print 'Message could not be confirmed'
            
            print " [x] message Sent "
            connection.close()

        except:
            raise

        #finally:
            #os.remove(filename)

        nexttime=nexttime+datetime.timedelta(seconds=tloop)
        waitsec=min((nexttime - datetime.datetime.utcnow()).seconds,tloop)
        print "wait for:",waitsec
        time.sleep(waitsec)


if __name__ == '__main__':

    import sys, os
    composereportd.cwd=os.getcwd()

    if composereportd.service():

        sys.stdout.write("Daemon started with pid %d\n" % os.getpid())
        sys.stdout.write("Daemon stdout output\n")
        sys.stderr.write("Daemon stderr output\n")

        main(composereportd)  # (this code was run as script)

        for proc in composereportd.procs:
            proc.wait()

        sys.exit(0)
