import logging
import sys
import time
import traceback
from api_clients.api_client import AirtimeApiClient

def generate_liquidsoap_config(ss):
    data = ss['msg']
    fh = open('/etc/airtime/liquidsoap.cfg', 'w')
    fh.write("################################################\n")
    fh.write("# THIS FILE IS AUTO GENERATED. DO NOT CHANGE!! #\n")
    fh.write("################################################\n")
    fh.write("# The ignore() lines are to squash unused variable warnings\n")

    for key, value in data.iteritems():
        try:
            str_buffer = "%s = %s\n" % (key, int(value))
        except ValueError:
            try: # Is it a boolean?
                if "true" in value or "false" in value:
                    str_buffer = "%s = %s\n" % (key, value.lower())
                else:
                    raise ValueError() # Just drop into the except below
            except: #Everything else is a string
                str_buffer = "%s = \"%s\"\n" % (key, value)

        fh.write(str_buffer.encode('utf-8'))
        # ignore squashes unused variable errors from Liquidsoap
        fh.write(("ignore(%s)\n" % key).encode('utf-8'))

    fh.write('log_file = "/var/log/airtime/pypo-liquidsoap/<script>.log"\n')
    fh.close()

logging.basicConfig(format='%(message)s')
attempts = 0
max_attempts = 10
successful = False

while not successful:
    try:
        ac = AirtimeApiClient(logging.getLogger())
        ss = ac.get_stream_setting()
        generate_liquidsoap_config(ss)
        successful = True
    except Exception, e:
        if attempts == max_attempts:
            print "Unable to connect to the Airtime server."
            logging.error(str(e))
            logging.error("traceback: %s", traceback.format_exc())
            sys.exit(1)
        else:
            logging.error(str(e))
            logging.error("traceback: %s", traceback.format_exc())
            logging.info("Retrying in 3 seconds...")
            time.sleep(3)
    attempts += 1