# Path: otpsetup/client/models.py
# class AmazonMachineImage(models.Model):
#     ami_id = models.CharField(max_length=200)
#     machine_type = models.CharField(max_length=20, choices=MACHINE_TYPES)
#     version = models.CharField(max_length=20)
#     default_for_new_instances = models.BooleanField(max_length=20, default=True)
#     def save(self, force_insert=False, force_update=False):
#         if self.default_for_new_instances:
#             AmazonMachineImage.objects.filter(~Q(id = self.id) & Q(machine_type = self.machine_type)).update(default_for_new_instances=False)
#         super(Test, self).save(force_insert, force_update)
# 
# class InstanceRequestForm(ModelForm):
#     fare_factory = RegexField(label="Fare model", max_length=200, 
#                              regex=r'^[\w.]+')
# 
#     class Meta:
#         model = InstanceRequest
#         fields = ('comments', 'agency', 'fare_factory')
# 
# class InstanceRequest(models.Model):
#     state = models.CharField(max_length=15, default='building', choices = STATES)
#     submit_date = models.DateTimeField('date submitted', default=datetime.now)
#     decision_date = models.DateTimeField('date decided', null=True)
# 
#     user = models.ForeignKey(User)
#     agency = models.CharField(max_length=40, blank=True)
#     comments = models.TextField(max_length=20000, null=True, blank=True)
#     fare_factory = models.CharField(max_length=200)
#     deployment_hostname = models.CharField(max_length=30, null=True, blank=True)
#     admin_password = models.CharField(max_length=15, null=True, blank=True)
#     public_url = models.CharField(max_length=60, null=True, blank=True)
#     graph_key = models.CharField(max_length=60, null=True, blank=True)
#     data_key = models.CharField(max_length=60, null=True, blank=True)
#     graph_url = models.CharField(max_length=150, null=True, blank=True)
#     ip = models.CharField(max_length=15)
#     deployment_host = models.ForeignKey(DeploymentHost, null=True, blank=True)
#     otp_version = models.CharField(max_length=20, null=True, blank=True)
# 
#     __original_dephost = None
# 
#     def __init__(self, *args, **kwargs):
#         super(InstanceRequest, self).__init__(*args, **kwargs)
#         self.__original_dephost = self.deployment_host
# 
#     def save(self, force_insert=False, force_update=False):
#         if self.deployment_host != self.__original_dephost and self.deployment_host is not None:
#             # dephost changed - publish deployer message
#             exchange = Exchange("amq.direct", type="direct", durable=True)
#             conn = DjangoBrokerConnection()
#             publisher = conn.Producer(routing_key="deploy_graph_multi", exchange=exchange)
#             publisher.publish({"request_id" : self.id, "instance_id" : self.deployment_host.instance_id, "graph_key" : self.graph_key})
# 
# 
#         super(InstanceRequest, self).save(force_insert, force_update)
#         self.__original_dephost = self.deployment_host
# 
# class GtfsFile(models.Model):
#     instance_request = models.ForeignKey(InstanceRequest)
#     s3_key = models.CharField(max_length=200, null=True, db_index=True)
#     transload_url = models.CharField(max_length=200, null=True)
#     validation_output = models.TextField(max_length=20000, null=True, blank=True)
#     extra_properties = models.TextField(max_length=2000, null=True, blank=True)
# 
#     def validation_output_str(self):
#         if(self.validation_output == None):
#             return "(None)"
#         return "<textarea rows=8 cols=85>%s</textarea>" % self.validation_output
#     validation_output_str.allow_tags = True


from boto import connect_s3, connect_ec2
from otpsetup.client.models import AmazonMachineImage, InstanceRequestForm, InstanceRequest, GtfsFile
from datetime import datetime, timedelta
from django.conf import settings
from django.contrib.auth.decorators import permission_required
from django.shortcuts import redirect
from json import dumps
from otpsetup.shortcuts import render_to_response
from otpsetup.shortcuts import DjangoBrokerConnection
import base64
import hmac, sha






@permission_required('admin')
def index(request):   
    conn = connect_ec2(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_KEY)
    reservations = conn.get_all_instances()
    running_instances = []
    for reservation in reservations:
        for instance in reservation.instances:
            image = AmazonMachineImage.objects.get(ami_id=instance.image_id)
            running_instances.append(dict(image=image, instance=instance))


# Path: otpsetup/client/models.py
# class AmazonMachineImage(models.Model):
#     ami_id = models.CharField(max_length=200)
#     machine_type = models.CharField(max_length=20, choices=MACHINE_TYPES)
#     version = models.CharField(max_length=20)
#     default_for_new_instances = models.BooleanField(max_length=20, default=True)
#     def save(self, force_insert=False, force_update=False):
#         if self.default_for_new_instances:
#             AmazonMachineImage.objects.filter(~Q(id = self.id) & Q(machine_type = self.machine_type)).update(default_for_new_instances=False)
#         super(Test, self).save(force_insert, force_update)
# 
# class InstanceRequestForm(ModelForm):
#     fare_factory = RegexField(label="Fare model", max_length=200, 
#                              regex=r'^[\w.]+')
# 
#     class Meta:
#         model = InstanceRequest
#         fields = ('comments', 'agency', 'fare_factory')
# 
# class InstanceRequest(models.Model):
#     state = models.CharField(max_length=15, default='building', choices = STATES)
#     submit_date = models.DateTimeField('date submitted', default=datetime.now)
#     decision_date = models.DateTimeField('date decided', null=True)
# 
#     user = models.ForeignKey(User)
#     agency = models.CharField(max_length=40, blank=True)
#     comments = models.TextField(max_length=20000, null=True, blank=True)
#     fare_factory = models.CharField(max_length=200)
#     deployment_hostname = models.CharField(max_length=30, null=True, blank=True)
#     admin_password = models.CharField(max_length=15, null=True, blank=True)
#     public_url = models.CharField(max_length=60, null=True, blank=True)
#     graph_key = models.CharField(max_length=60, null=True, blank=True)
#     data_key = models.CharField(max_length=60, null=True, blank=True)
#     graph_url = models.CharField(max_length=150, null=True, blank=True)
#     ip = models.CharField(max_length=15)
#     deployment_host = models.ForeignKey(DeploymentHost, null=True, blank=True)
#     otp_version = models.CharField(max_length=20, null=True, blank=True)
# 
#     __original_dephost = None
# 
#     def __init__(self, *args, **kwargs):
#         super(InstanceRequest, self).__init__(*args, **kwargs)
#         self.__original_dephost = self.deployment_host
# 
#     def save(self, force_insert=False, force_update=False):
#         if self.deployment_host != self.__original_dephost and self.deployment_host is not None:
#             # dephost changed - publish deployer message
#             exchange = Exchange("amq.direct", type="direct", durable=True)
#             conn = DjangoBrokerConnection()
#             publisher = conn.Producer(routing_key="deploy_graph_multi", exchange=exchange)
#             publisher.publish({"request_id" : self.id, "instance_id" : self.deployment_host.instance_id, "graph_key" : self.graph_key})
# 
# 
#         super(InstanceRequest, self).save(force_insert, force_update)
#         self.__original_dephost = self.deployment_host
# 
# class GtfsFile(models.Model):
#     instance_request = models.ForeignKey(InstanceRequest)
#     s3_key = models.CharField(max_length=200, null=True, db_index=True)
#     transload_url = models.CharField(max_length=200, null=True)
#     validation_output = models.TextField(max_length=20000, null=True, blank=True)
#     extra_properties = models.TextField(max_length=2000, null=True, blank=True)
# 
#     def validation_output_str(self):
#         if(self.validation_output == None):
#             return "(None)"
#         return "<textarea rows=8 cols=85>%s</textarea>" % self.validation_output
#     validation_output_str.allow_tags = True


# Path: otpsetup/client/manage_ec2.py
from boto import connect_s3, connect_ec2
from otpsetup.client.models import AmazonMachineImage, InstanceRequestForm, InstanceRequest, GtfsFile
from datetime import datetime, timedelta
from django.conf import settings
from django.contrib.auth.decorators import permission_required
from django.shortcuts import redirect
from json import dumps
from otpsetup.shortcuts import render_to_response
from otpsetup.shortcuts import DjangoBrokerConnection
import base64
import hmac, sha







@permission_required('admin')
def index(request):   
    conn = connect_ec2(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_KEY)
    reservations = conn.get_all_instances()
    running_instances = []
    for reservation in reservations:
        for instance in reservation.instances:
            image = AmazonMachineImage.objects.get(ami_id=instance.image_id)
            running_instances.append(dict(image=image, instance=instance))


    images = AmazonMachineImage.objects.all()