# Path: simulator/models.py
# class simulation(models.Model):
#     
#     account = models.ForeignKey(User, on_delete=models.CASCADE,editable=False)
#     description= models.CharField(max_length=50, default="")
#     process_name =models.CharField(max_length=50,default="")
#     start_time=models.DateTimeField()
#     end_time=models.DateTimeField(default=timezone.now)
#     period=models.IntegerField(default=1,help_text="period between updates in seconds")
#     
#     def __str__(self):
#         return self.description
# 
# class thing (models.Model):
#     
#     simulation = models.ForeignKey('simulation',on_delete=models.CASCADE)
#     device=models.ForeignKey('devices.device',on_delete=models.CASCADE)
#     target= models.FloatField(default=0)
#     month_k=models.FloatField(default=1,help_text="positive greater in winter")
#     hour_k=models.FloatField(default=1,help_text="positive greater in daytime")
#     longwave_k=models.FloatField(default=10000,help_text="positive integer large number longer wave")
#     longwave_a=models.FloatField(default=1,help_text="positive - higher wave variation")
#     last_v=models.FloatField(default=0)
#     delta_v=models.FloatField(default=0)
#     d_delta_v=models.FloatField(default=0)
#     ra=models.FloatField(default=0,help_text="higher number more random")
#     ce=models.FloatField(default=0,help_text="higher number more centred")
# 
# Path: devices/models.py
# class Device(models.Model):
#     account = models.ForeignKey(User, on_delete=models.CASCADE,editable=False)
#     device_id=models.CharField(unique=True,max_length=50,validators=[alphanumeric],help_text="device should publish to mqtt on account_name/deviceID/appID/channelID")
#     device_desc = models.CharField(max_length=50,blank=True)
#     section = models.ForeignKey(Section, on_delete=models.CASCADE)
#     group=models.CharField(max_length=50,blank=True)
#     subgroup=models.CharField(max_length=50,blank=True)
#     latitude=models.FloatField(blank=True,null=True)
#     longitude=models.FloatField(blank=True,null=True)
#     model_name = models.CharField(max_length=50,blank=True)
#     install_date = models.DateTimeField('install_date',default=timezone.now)
# 
# 
#     def __str__(self):
#         return self.device_id
# 
# class Channel(models.Model):
#     device = models.ForeignKey(Device, on_delete=models.CASCADE)
#     channel_id=models.CharField(max_length=50,validators=[alphanumeric],help_text="device should publish to mqtt on account_name/deviceID/appID/channelID")
#     channel_desc = models.CharField(max_length=50,blank=True)
#     channel_tags = models.ManyToManyField(Channel_tag,blank=True)
#     time_tag_year=models.BooleanField(default=False,help_text="tags the channel data with year (eg.\'2015\')")
#     time_tag_month=models.BooleanField(default=False,help_text="tags the channel data with month")
#     time_tag_day=models.BooleanField(default=False,help_text="tags the channel data with day of week")
#     time_tag_hour=models.BooleanField(default=False,help_text="tags the channel data with hour (eg.\'2015\')")
#     elapsed_since_same_ch=models.BooleanField(default=False,help_text="tags the channel data with seconds since any data was received on SAME channel(eg.cycle time)')")
#     elapsed_since_diff_ch=models.BooleanField(default=False,help_text="tags the channel data with seconds since HOOK was received on DIFFERENT channel(for TIME betwen different processes typically RFID')")
#     
#     upper_warning=models.FloatField(blank=True,null=True)
#     lower_warning=models.FloatField(blank=True,null=True)
#     alarm_logs=models.BooleanField(default=False)
#     alarm_email=models.BooleanField(default=False,help_text="alarms will be sent to user who owns device (not active)")
#     alarm_raised=models.DateTimeField(default=timezone.now)
#     
#     def __str__(self):
#         return self.channel_id
#      
#     def last_published(self):
#         mytime= getLastTimeInflux("dab"+str(self.device.account.username),self.device.device_id,self.channel_id)
#         
#         return mytime
# 
# class Section(models.Model):
#     account = models.ForeignKey(User, on_delete=models.CASCADE,editable=False)
#     section_desc = models.CharField(max_length=50)
#     
#     def __str__(self):
#         return self.section_desc
# 
# Path: stack_configs/models.py
# def sendToRabbitMQ(topic,message):
# 
#     cp=getRabbitConnection()    
#     connection = pika.BlockingConnection(cp)
#     channel = connection.channel()
#     routing_key= topic
#         
#     channel.basic_publish(exchange='amq.topic',
#                       routing_key=routing_key,
#                       body=message)
#     result=(" [x] Sent %r:%r" % (routing_key,message))
#     connection.close()
#             
#     return result


from django.core.management.base import BaseCommand, CommandError
from django.utils import timezone
from django.utils.dateparse import parse_datetime
from simulator.models import simulation,thing
from devices.models import Device,Channel,Section
from stack_configs.models import sendToRabbitMQ
from django.contrib.auth.models import User
from random import randint
import datetime
import time
import random
import json
import string
import logging

global simulation_account
try:
    simulation_account=User.objects.filter(username='simulation')[0]
    
except:
    logger.info('no user account named simulation found, aborting')
    raise SystemExit(0)


#global simulationAccount


class Command(BaseCommand):
    help = 'updates all simulations and sends to rabbitMQ'

       
    
    def handle(self, *args, **options):
                    
            
        logger.info('starting handle update simulation')
        while True:
            output=getAllSims()
            time.sleep(100)
            logger.info('simulation completed, sleeping')
           
def getAllSims():
#get all simulation objects and calculate from last start time up till now 
    #try:

# Path: simulator/models.py
# class simulation(models.Model):
#     
#     account = models.ForeignKey(User, on_delete=models.CASCADE,editable=False)
#     description= models.CharField(max_length=50, default="")
#     process_name =models.CharField(max_length=50,default="")
#     start_time=models.DateTimeField()
#     end_time=models.DateTimeField(default=timezone.now)
#     period=models.IntegerField(default=1,help_text="period between updates in seconds")
#     
#     def __str__(self):
#         return self.description
# 
# class thing (models.Model):
#     
#     simulation = models.ForeignKey('simulation',on_delete=models.CASCADE)
#     device=models.ForeignKey('devices.device',on_delete=models.CASCADE)
#     target= models.FloatField(default=0)
#     month_k=models.FloatField(default=1,help_text="positive greater in winter")
#     hour_k=models.FloatField(default=1,help_text="positive greater in daytime")
#     longwave_k=models.FloatField(default=10000,help_text="positive integer large number longer wave")
#     longwave_a=models.FloatField(default=1,help_text="positive - higher wave variation")
#     last_v=models.FloatField(default=0)
#     delta_v=models.FloatField(default=0)
#     d_delta_v=models.FloatField(default=0)
#     ra=models.FloatField(default=0,help_text="higher number more random")
#     ce=models.FloatField(default=0,help_text="higher number more centred")
# 
# Path: devices/models.py
# class Device(models.Model):
#     account = models.ForeignKey(User, on_delete=models.CASCADE,editable=False)
#     device_id=models.CharField(unique=True,max_length=50,validators=[alphanumeric],help_text="device should publish to mqtt on account_name/deviceID/appID/channelID")
#     device_desc = models.CharField(max_length=50,blank=True)
#     section = models.ForeignKey(Section, on_delete=models.CASCADE)
#     group=models.CharField(max_length=50,blank=True)
#     subgroup=models.CharField(max_length=50,blank=True)
#     latitude=models.FloatField(blank=True,null=True)
#     longitude=models.FloatField(blank=True,null=True)
#     model_name = models.CharField(max_length=50,blank=True)
#     install_date = models.DateTimeField('install_date',default=timezone.now)
# 
# 
#     def __str__(self):
#         return self.device_id
# 
# class Channel(models.Model):
#     device = models.ForeignKey(Device, on_delete=models.CASCADE)
#     channel_id=models.CharField(max_length=50,validators=[alphanumeric],help_text="device should publish to mqtt on account_name/deviceID/appID/channelID")
#     channel_desc = models.CharField(max_length=50,blank=True)
#     channel_tags = models.ManyToManyField(Channel_tag,blank=True)
#     time_tag_year=models.BooleanField(default=False,help_text="tags the channel data with year (eg.\'2015\')")
#     time_tag_month=models.BooleanField(default=False,help_text="tags the channel data with month")
#     time_tag_day=models.BooleanField(default=False,help_text="tags the channel data with day of week")
#     time_tag_hour=models.BooleanField(default=False,help_text="tags the channel data with hour (eg.\'2015\')")
#     elapsed_since_same_ch=models.BooleanField(default=False,help_text="tags the channel data with seconds since any data was received on SAME channel(eg.cycle time)')")
#     elapsed_since_diff_ch=models.BooleanField(default=False,help_text="tags the channel data with seconds since HOOK was received on DIFFERENT channel(for TIME betwen different processes typically RFID')")
#     
#     upper_warning=models.FloatField(blank=True,null=True)
#     lower_warning=models.FloatField(blank=True,null=True)
#     alarm_logs=models.BooleanField(default=False)
#     alarm_email=models.BooleanField(default=False,help_text="alarms will be sent to user who owns device (not active)")
#     alarm_raised=models.DateTimeField(default=timezone.now)
#     
#     def __str__(self):
#         return self.channel_id
#      
#     def last_published(self):
#         mytime= getLastTimeInflux("dab"+str(self.device.account.username),self.device.device_id,self.channel_id)
#         
#         return mytime
# 
# class Section(models.Model):
#     account = models.ForeignKey(User, on_delete=models.CASCADE,editable=False)
#     section_desc = models.CharField(max_length=50)
#     
#     def __str__(self):
#         return self.section_desc
# 
# Path: stack_configs/models.py
# def sendToRabbitMQ(topic,message):
# 
#     cp=getRabbitConnection()    
#     connection = pika.BlockingConnection(cp)
#     channel = connection.channel()
#     routing_key= topic
#         
#     channel.basic_publish(exchange='amq.topic',
#                       routing_key=routing_key,
#                       body=message)
#     result=(" [x] Sent %r:%r" % (routing_key,message))
#     connection.close()
#             
#     return result


# Path: simulator/management/commands/update_simulations.py
from django.core.management.base import BaseCommand, CommandError
from django.utils import timezone
from django.utils.dateparse import parse_datetime
from simulator.models import simulation,thing
from devices.models import Device,Channel,Section
from stack_configs.models import sendToRabbitMQ
from django.contrib.auth.models import User
from random import randint
import datetime
import time
import random
import json
import string
import logging


global simulation_account
try:
    simulation_account=User.objects.filter(username='simulation')[0]
    
except:
    logger.info('no user account named simulation found, aborting')
    raise SystemExit(0)


#global simulationAccount


class Command(BaseCommand):
    help = 'updates all simulations and sends to rabbitMQ'

       
    
    def handle(self, *args, **options):
                    
            
        logger.info('starting handle update simulation')
        while True:
            output=getAllSims()
            time.sleep(100)
            logger.info('simulation completed, sleeping')
           
def getAllSims():
#get all simulation objects and calculate from last start time up till now 
    #try:

    sims=simulation.objects.all()