"""
ec2.connection
~~~~~~~~~~~~~~

:copyright: (c) 2014 by Matt Robenolt.
:license: BSD, see LICENSE for more details.
"""

import os
import boto.ec2
import boto.vpc

_connection = None
_vpc_connection = None


def get_connection():
    "Cache a global connection object to be used by all classes"
    global _connection
    if _connection is None:
        _connection = boto.ec2.connect_to_region(**credentials())
    return _connection


def get_vpc_connection():
    global _vpc_connection
    if _vpc_connection is None:
        _vpc_connection = boto.vpc.connect_to_region(**credentials())
    return _vpc_connection


class credentials(object):
    """
    Simple credentials singleton that holds our fun AWS info
    and masquerades as a dict
    """
    ACCESS_KEY_ID = None
    SECRET_ACCESS_KEY = None
    REGION_NAME = 'us-east-1'

    def keys(self):
        return ['aws_access_key_id', 'aws_secret_access_key', 'region_name']

    def __getitem__(self, item):
        item = item.upper()
        return (
            os.environ.get(item) or
            getattr(self, item, None) or
            getattr(self, item[4:])
        )

    @classmethod
    def from_file(cls, filename):
        """
        Load ACCESS_KEY_ID and SECRET_ACCESS_KEY from csv
        generated by Amazon's IAM.

        >>> ec2.credentials.from_file('credentials.csv')
        """
        import csv
        with open(filename, 'r') as f:
            reader = csv.DictReader(f)
            row = reader.next()  # Only one row in the file
        try:
            cls.ACCESS_KEY_ID = row['Access Key Id']
            cls.SECRET_ACCESS_KEY = row['Secret Access Key']
        except KeyError:
            raise IOError('Invalid credentials format')
