# Simple example of recreating similar groups on Adafruit IO with the REST API client.
# Author: Tyeth Gundry

# Import Adafruit IO REST client.
from adafruit_io import Client, Feed, Group
import json
import os

# Set to your Adafruit IO key.
# Remember, your key is a secret,
# so make sure not to publish it when you publish this code!
ADAFRUIT_IO_KEY = os.getenv('ADAFRUIT_IO_KEY', 'YOUR_AIO_KEY')

# Set to your Adafruit IO username.
# (go to https://accounts.adafruit.com to find your username)
ADAFRUIT_IO_USERNAME = os.getenv('ADAFRUIT_IO_USERNAME', 'YOUR_AIO_USERNAME')

# Set to the group key you want to copy
ADAFRUIT_IO_GROUP_KEY = os.getenv('ADAFRUIT_IO_GROUP_KEY', 'enviro')

# new group name template {number} will be replaced with the group number
ADAFRUIT_IO_NEW_GROUP_NAME = os.getenv('ADAFRUIT_IO_NEW_GROUP_NAME', 'enviro {number}')

# new group starting number and count of groups to create
ADAFRUIT_IO_NEW_GROUP_START = int(os.getenv('ADAFRUIT_IO_NEW_GROUP_START', 2))
ADAFRUIT_IO_NEW_GROUP_COUNT = int(os.getenv('ADAFRUIT_IO_NEW_GROUP_COUNT', 19))


# Create an instance of the REST client.
aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)

# Fetch group to be copied
main_group = aio.groups(ADAFRUIT_IO_GROUP_KEY)
if main_group is None:
    print(f"Group not found, try visiting https://io.adafruit.com/{ADAFRUIT_IO_USERNAME}/feeds and viewing the group info to find the key")
    exit()

if main_group.feeds in [None, []]:
    print(f"Group {ADAFRUIT_IO_GROUP_KEY} has no feeds")
    exit()

for i in range(ADAFRUIT_IO_NEW_GROUP_START, ADAFRUIT_IO_NEW_GROUP_START + (ADAFRUIT_IO_NEW_GROUP_COUNT-1)):
    new_group_name = ADAFRUIT_IO_NEW_GROUP_NAME.format(number=i)
    print(f"Creating group {new_group_name}")
    new_group = aio.create_group(Group(name=new_group_name))
    new_group_key = new_group.key
    print(f"New group created: {new_group.name} (key: {new_group_key})")

    # Create feeds in the new group
    for feed in main_group.feeds:
        print(f"Creating feed {feed.name} in group {new_group_key}")
        new_feed = Feed(name=feed.name)
        response = aio.create_feed(new_feed, new_group_key)
        print(f"created new feed {new_feed.name} in group {new_group_key}")