#!/usr/bin/env python
# -*- coding: utf-8 -*-
# $Id: Amazon.py 9439 2015-09-25 08:01:30Z Eric $
#
# Copyright (c) 2015 Nuwa Information Co., Ltd, All Rights Reserved.
#
# Licensed under the Proprietary License,
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at our web site.
#
# See the License for the specific language governing permissions and
# limitations under the License.
#
# $Author: Eric $ (last)
# $Date: 2015-09-25 16:01:30 +0800 (Fri, 25 Sep 2015) $
# $Revision: 9439 $

import os

from boto import ec2

from Iuppiter.Util import preferredSort

from Iuno.cloud.backend import BaseBackend

class Backend(BaseBackend):

    # Read-only permission.
    AWS_ACCESS_KEY_ID = "AKIAIBRY5O6ZE6V6L2SQ"
    AWS_SECRET_ACCESS_KEY = "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"

    # EC2 stateful controller first.
    DEFAULT_PREFERRED_DOMAINS = (
        'i-1ea2b35a',
    )

    INSTANCES_REGION = {
        'i-1ea2b35a': 'us-west-1',
    }

    def getRegions(self):
        """
        Get all AWS regions.

        @return Region names.
        """
        regions = self._readCache('regions')
        if regions:
            self.logger.info('REGIONS: %s (from cache)' % str(regions))
            return regions

        regions = ec2.regions(aws_access_key_id=self.AWS_ACCESS_KEY_ID,
                              aws_secret_access_key=self.AWS_SECRET_ACCESS_KEY)
        regions = [r.name for r in regions]

        self.logger.info('REGIONS: %s' % str(regions))
        self._writeCache('regions', regions)

        return regions

    def getDomains(self, preferred=None):
        preferred = self._adjustPreferred(preferred)

        d = self._readCache('idDnsDict')
        if d:
            self.logger.info('INSTANCES: %s (from cache)' % str(d.keys()))
        else:
            regions = self.getRegions()
            reservations = []
            for region in regions:
                conn = ec2.connect_to_region(region,
                    aws_access_key_id=self.AWS_ACCESS_KEY_ID,
                    aws_secret_access_key=self.AWS_SECRET_ACCESS_KEY)
                reservations.extend(conn.get_all_instances())

            instances = []
            for r in reservations:
                for inst in r.instances:
                    if inst.state == 'running':
                        instances.append(inst)

            d = dict([(i.id, i.public_dns_name) for i in instances])

            self.logger.info('INSTANCES: %s' % str(d.keys()))
            self._writeCache('idDnsDict', d, expire=86400) # expire 1 day.

        values = d.keys()

        preferredSort(values, preferred)
        return [d[v] for v in values]

    def attachSettings(self, settingsLocals):
        # http://code.google.com/p/boto/wiki/BotoConfig
        if 'BOTO_CONFIG' not in os.environ and 'BOTO_PATH' not in os.environ:
            settingsLocals.update({
                'AWS_ACCESS_KEY_ID': self.AWS_ACCESS_KEY_ID,
                'AWS_SECRET_ACCESS_KEY': self.AWS_SECRET_ACCESS_KEY,
            })
