# Path: handson/myyaml.py
# def stanza(k, new_val=None):
#     global _cache
#     load()
#     if new_val is not None:
#         assert k in tree_stanzas.keys(), (
#             "YAML stanza {!r} not permitted".format(k)
#         )
#         _cache[k] = new_val
#         write()
#     stanza_is_sane(k)
#     return _cache[k]
# 
# Path: handson/tag.py
# def apply_tag(obj, tag='Name', val=None):
#     """
#         tag an AWS object
#     """
#     for x in [1, 1, 2, 4, 8]:
#         error = False
#         try:
#             obj.add_tag(tag, val)
#         except:  # pragma: no cover
#             error = True
#             e = sys.exc_info()[0]
#             log.info("Huh, trying again ({})".format(e))
#             time.sleep(x)
#         if not error:
#             log.info("Object {} tagged with {}={}".format(obj, tag, val))
#             break
#     return None
# 
# Path: handson/vpc.py
# class VPC(Region):
# 
#     def __init__(self, args):
#         super(VPC, self).__init__(args)
#         self.args = args
#         self._vpc = {
#             'vpc_obj': None
#         }
# 
#     def vpc_obj(self, create=False, dry_run=False, quiet=False):
#         """
#             fetch VPC object, create if necessary
#         """
#         #
#         # cached VPC object
#         if self._vpc['vpc_obj'] is not None:
#             return self._vpc['vpc_obj']
#         #
#         # non-cached
#         vpc_stanza = stanza('vpc')
#         vpc_conn = self.vpc()
#         if len(vpc_stanza) == 0:  # pragma: no cover
#             #
#             # create VPC
#             if create:
#                 if dry_run:
#                     log.info("Dry run: do nothing")
#                     vpc_obj = None
#                 else:
#                     log.info("VPC ID not specified in yaml: creating VPC")
#                     vpc_obj = vpc_conn.create_vpc('10.0.0.0/16')
#                     vpc_stanza['id'] = vpc_obj.id
#                     vpc_stanza['cidr_block'] = vpc_obj.cidr_block
#                     log.info("New VPC ID {} created with CIDR block {}".format(
#                         vpc_obj.id, vpc_obj.cidr_block
#                     ))
#                     apply_tag(vpc_obj, tag='Name', val=stanza('nametag'))
#                     self._vpc['vpc_obj'] = vpc_obj
#                     stanza('vpc', {
#                         'cidr_block': vpc_obj.cidr_block,
#                         'id': vpc_obj.id
#                     })
#                     vpc_conn.modify_vpc_attribute(
#                         vpc_obj.id,
#                         enable_dns_support=True,
#                     )
#                     vpc_conn.modify_vpc_attribute(
#                         vpc_obj.id,
#                         enable_dns_hostnames=True,
#                     )
#             else:
#                 log.info("VPC ID not specified in yaml: nothing to do")
#                 vpc_obj = None
#             return vpc_obj
#         #
#         # existing VPC
#         log.debug("VPD ID specified in yaml: fetching it")
#         vpc_id = vpc_stanza['id']
#         if not quiet:
#             log.info("VPC ID according to yaml is {}".format(vpc_id))
#         vpc_list = vpc_conn.get_all_vpcs(vpc_ids=vpc_id)
#         assert len(vpc_list) == 1, (
#                "VPC ID {} does not exist".format(vpc_id))
#         vpc_obj = vpc_list[0]
#         cidr_block = vpc_obj.cidr_block
#         assert cidr_block == '10.0.0.0/16', (
#                ("VPC ID {} exists, but has wrong CIDR block {} "
#                 "(should be 10.0.0.0/16)").format(vpc_id, cidr_block))
#         if not quiet:
#             log.info("VPC ID is {}, CIDR block is {}".format(
#                 vpc_stanza['id'], vpc_stanza['cidr_block'],
#             ))
#         self._vpc['vpc_obj'] = vpc_obj
#         vpc_conn.modify_vpc_attribute(
#             vpc_obj.id,
#             enable_dns_support=True,
#         )
#         vpc_conn.modify_vpc_attribute(
#             vpc_obj.id,
#             enable_dns_hostnames=True,
#         )
#         return vpc_obj
# 
#     def wipeout(self, dry_run=False):
#         vpc_obj = self.vpc_obj(create=False, dry_run=dry_run)
#         if vpc_obj and not dry_run:
#             log.info("Wiping out VPC ID {}".format(vpc_obj.id))
#             self.vpc().delete_vpc(vpc_obj.id)
#             stanza('vpc', {})
#         else:
#             log.info("No VPC in YAML; nothing to do")
#         return None


import logging
from handson.myyaml import stanza
from handson.tag import apply_tag
from handson.vpc import VPC
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#

# from handson.util import read_user_data

log = logging.getLogger(__name__)


class Subnet(VPC):

    def __init__(self, args, delegate):
        super(Subnet, self).__init__(args)
        self.args = args
        self._subnet = {
            'delegate': delegate,
            's_obj': None
        }

    def subnet_obj(self, create=False, dry_run=False):
        """
            Subnet object is returned from cache if cached.
            Otherwise, the method validates the subnet, creates it if
            necessary, populates tree, and returns subnet object.
        """
        if self._subnet['s_obj']:
            return self._subnet['s_obj']

# Path: handson/myyaml.py
# def stanza(k, new_val=None):
#     global _cache
#     load()
#     if new_val is not None:
#         assert k in tree_stanzas.keys(), (
#             "YAML stanza {!r} not permitted".format(k)
#         )
#         _cache[k] = new_val
#         write()
#     stanza_is_sane(k)
#     return _cache[k]
# 
# Path: handson/tag.py
# def apply_tag(obj, tag='Name', val=None):
#     """
#         tag an AWS object
#     """
#     for x in [1, 1, 2, 4, 8]:
#         error = False
#         try:
#             obj.add_tag(tag, val)
#         except:  # pragma: no cover
#             error = True
#             e = sys.exc_info()[0]
#             log.info("Huh, trying again ({})".format(e))
#             time.sleep(x)
#         if not error:
#             log.info("Object {} tagged with {}={}".format(obj, tag, val))
#             break
#     return None
# 
# Path: handson/vpc.py
# class VPC(Region):
# 
#     def __init__(self, args):
#         super(VPC, self).__init__(args)
#         self.args = args
#         self._vpc = {
#             'vpc_obj': None
#         }
# 
#     def vpc_obj(self, create=False, dry_run=False, quiet=False):
#         """
#             fetch VPC object, create if necessary
#         """
#         #
#         # cached VPC object
#         if self._vpc['vpc_obj'] is not None:
#             return self._vpc['vpc_obj']
#         #
#         # non-cached
#         vpc_stanza = stanza('vpc')
#         vpc_conn = self.vpc()
#         if len(vpc_stanza) == 0:  # pragma: no cover
#             #
#             # create VPC
#             if create:
#                 if dry_run:
#                     log.info("Dry run: do nothing")
#                     vpc_obj = None
#                 else:
#                     log.info("VPC ID not specified in yaml: creating VPC")
#                     vpc_obj = vpc_conn.create_vpc('10.0.0.0/16')
#                     vpc_stanza['id'] = vpc_obj.id
#                     vpc_stanza['cidr_block'] = vpc_obj.cidr_block
#                     log.info("New VPC ID {} created with CIDR block {}".format(
#                         vpc_obj.id, vpc_obj.cidr_block
#                     ))
#                     apply_tag(vpc_obj, tag='Name', val=stanza('nametag'))
#                     self._vpc['vpc_obj'] = vpc_obj
#                     stanza('vpc', {
#                         'cidr_block': vpc_obj.cidr_block,
#                         'id': vpc_obj.id
#                     })
#                     vpc_conn.modify_vpc_attribute(
#                         vpc_obj.id,
#                         enable_dns_support=True,
#                     )
#                     vpc_conn.modify_vpc_attribute(
#                         vpc_obj.id,
#                         enable_dns_hostnames=True,
#                     )
#             else:
#                 log.info("VPC ID not specified in yaml: nothing to do")
#                 vpc_obj = None
#             return vpc_obj
#         #
#         # existing VPC
#         log.debug("VPD ID specified in yaml: fetching it")
#         vpc_id = vpc_stanza['id']
#         if not quiet:
#             log.info("VPC ID according to yaml is {}".format(vpc_id))
#         vpc_list = vpc_conn.get_all_vpcs(vpc_ids=vpc_id)
#         assert len(vpc_list) == 1, (
#                "VPC ID {} does not exist".format(vpc_id))
#         vpc_obj = vpc_list[0]
#         cidr_block = vpc_obj.cidr_block
#         assert cidr_block == '10.0.0.0/16', (
#                ("VPC ID {} exists, but has wrong CIDR block {} "
#                 "(should be 10.0.0.0/16)").format(vpc_id, cidr_block))
#         if not quiet:
#             log.info("VPC ID is {}, CIDR block is {}".format(
#                 vpc_stanza['id'], vpc_stanza['cidr_block'],
#             ))
#         self._vpc['vpc_obj'] = vpc_obj
#         vpc_conn.modify_vpc_attribute(
#             vpc_obj.id,
#             enable_dns_support=True,
#         )
#         vpc_conn.modify_vpc_attribute(
#             vpc_obj.id,
#             enable_dns_hostnames=True,
#         )
#         return vpc_obj
# 
#     def wipeout(self, dry_run=False):
#         vpc_obj = self.vpc_obj(create=False, dry_run=dry_run)
#         if vpc_obj and not dry_run:
#             log.info("Wiping out VPC ID {}".format(vpc_obj.id))
#             self.vpc().delete_vpc(vpc_obj.id)
#             stanza('vpc', {})
#         else:
#             log.info("No VPC in YAML; nothing to do")
#         return None


# Path: handson/subnet.py
import logging
from handson.myyaml import stanza
from handson.tag import apply_tag
from handson.vpc import VPC

# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#

# from handson.util import read_user_data

log = logging.getLogger(__name__)


class Subnet(VPC):

    def __init__(self, args, delegate):
        super(Subnet, self).__init__(args)
        self.args = args
        self._subnet = {
            'delegate': delegate,
            's_obj': None
        }

    def subnet_obj(self, create=False, dry_run=False):
        """
            Subnet object is returned from cache if cached.
            Otherwise, the method validates the subnet, creates it if
            necessary, populates tree, and returns subnet object.
        """
        if self._subnet['s_obj']:
            return self._subnet['s_obj']

        s_stanza = stanza('subnets')