import json, requests, datetime, time
from api_auth import APICredentials, APIParams
channel_id = 'Hak3zjnPLSW5o0j8GMpzRMsa' # Replace with the ID for the desired live channel.
playlist_id = 'gh35hs89274748j2ab459ne7ud4f6cl3' # Replace with the ID for the desired playlist.

def convert_ts(utc_tstamp):
    """
        Convert a UTC timestamp to ISO 8601 format (YYYY-MM-DDThh:mm:ss.sZ).
        :param utc_tstamp: The UTC timestamp to convert (expected milliseconds)
    """
    iso_format = "%Y-%m-%dT%H:%M:%S.%fZ"
    try:
        _ts = float("{0:.3f}".format(utc_tstamp/1000.0))
        return "{}{}".format(datetime.datetime.utcfromtimestamp(_ts).strftime(iso_format)[:-4], "Z")
    except Exception:
        print ("Invalid timestamp: {}".format(utc_tstamp))
        raise

class ScheduleEntries:
    def __init__(self):
        self.host = "https://services.uplynk.com"

    def run(self):
        """
        Create mulitple schedule entries.
        """
        self._create_schedule_entries_by_playlist()

    def _create_schedule_entries_by_playlist(self):
        url = "{}{}{}{}".format(self.host, "/api/v4/channels/", channel_id, "/schedule-playlist")

        start = int((time.time() + 3600) * 1000.0) # 1 hour from now
        start = convert_ts(start)

        payload = {
            'playlist_id': playlist_id,            
            'start': start
        }

        headers = {'Content-Type': 'application/json'}

        response = requests.post(
            url, params=APIParams(APICredentials()).get_params({}), data=json.dumps(payload), headers=headers 
        )

        print(response.json())

ScheduleEntries().run()