import json, time, re

def formatLength(data, length):
    if (isinstance(data, str)):
        return data[0:length]
    else:
        return data
        
def dumpAndEncode(data):
    if (isinstance(data, str)):
        return json.dumps(re.sub(r'[^\x00-\x7f]',r' ',data))
    return json.dumps(data)
        
file = open('feed.json', 'r')
dump = json.load(file)
out = open('feed.sql', 'w');
out.write('/* This file was generated by json_feed_to_sql.py */\n\n')
for entry in dump:
    out.write('INSERT INTO Event (Admin_id, Category_id, ')
    out.write('Date_time, Name, Type, Contact_email, Contact_phone, ')
    out.write('Description, Approved) VALUES (1, 1, \'')
    when = time.strptime(entry['starts'], '%a, %d %b %Y %H:%M:%S %z')
    whenStr = time.strftime('%Y-%m-%d %H:00:00', when)
    out.write(whenStr)
    out.write('\', ' + dumpAndEncode(formatLength(entry['title'], 50)))
    out.write(', 1')
    out.write(', ' + dumpAndEncode(formatLength(entry['contact_email'], 50)))
    phone = dumpAndEncode(formatLength(entry['contact_phone'], 11))
    if (phone != 'null'):
        phone = '\'' + re.sub(r"\D", "", phone) + '\''
    out.write(', ' + phone)
    out.write(', ' + dumpAndEncode(formatLength(entry['description'], 160)))
    out.write(', 1);\n')
    