#!/usr/bin/python

from __future__ import print_function
import sys
import os
import time
import skew
from skew.arn import ARN
import threading
from threading import Thread
import resource
import json
from datetime import date, datetime
from functools import partial
import argparse

error = partial(print, file=sys.stderr)
costly = False
freeServices = ['autoscaling', 'elasticbeanstalk', 'iam']
freeResources = ['security-group', 'key-pair', 'network-acl', 'route-table', 'vpc', 'subnet-group', 'secgrp', 'subscription']

class Worker(Thread):
    def __init__(self, service, arn):
        Thread.__init__(self)
        self.arn = ARN(arn)
        self.name = arn
        self.service = service

    def run(self):
        for resource in self.arn.resource.choices():
            if args.costly and resource in freeResources:
                continue
            uri = ':'.join(['arn', 'aws', str(self.service), str(arn.region), str(arn.account), resource + '/*'])
            for i in skew.scan(uri):
                data = i.data
                print(json.dumps({ "arn": i.arn, "data": json.dumps(data, default=json_serial)}))

parser = argparse.ArgumentParser(description='Show all AWS resources.')
parser.add_argument('--arn', default='arn:aws:*:*:*:*', help='An ARN with wildcards to search for. Ex arn:aws:s3:*:*:*')
parser.add_argument('--costly', action='store_true', help='Ignore free services and resources')

args = parser.parse_args()
arn = ARN(args.arn)

for service in arn.service.choices():
    if args.costly and service in freeServices:
        continue
    uri = ':'.join(['arn', 'aws', service, str(arn.region), str(arn.account), str(arn.resource)])
    worker = Worker(service, uri)
    worker.start()

def json_serial(obj):
    """JSON serializer for objects not serializable by default json code"""

    if isinstance(obj, (datetime, date)):
        return obj.isoformat()
    raise TypeError ("Type %s not serializable" % type(obj))
