import sys
import json

if len(sys.argv) < 3:
    exit()

json_string = open(sys.argv[1], "r").read()

class SwiftVar:
    
    def __init__(self):
        self.name = ""
        self.type = ""
        self.collection = None

class SwiftObject:
    
    def __init__(self):
        self.name = ""
        self.vars = []

    def printClass(self):
    
        file = ""
    
        file += "class " + self.name + ": Mappable {\n"
        file += "\n"
        for var in self.vars:
            if var.collection == None:
                file += "\tvar " + var.name + ": "+ var.type + "!\n"
            else:
                file += "\tvar " + var.name + ": " + "["+var.collection+"]!\n" 

        file += "\n"
        file += '\tinit() {}\n'
        file += "\n"
        file += '\trequired init?(map: Map){}\n'
        file += "\n"
        file += '\tfunc mapping(map: Map) {\n'
        for var in self.vars:
            file += '\t\t'+var.name + ' <- map["'+ var.name + '"]\n'
        file += '\t}\n'
        file += "}\n"
        file += "\n"
        return file

object = SwiftObject()
object.name = sys.argv[2]

objects = [(object, json.loads(json_string))]

def to_camel_case(snake_str):
    components = snake_str.split('_')
    return components[0].title() + "".join(x.title() for x in components[1:])

def printDict(data):
    object = data[0]
    dictionary = None
    if isinstance(data[1], dict):
        dictionary = data[1]
    else:
        dictionary = data[1][0]    
    keys = dictionary.keys()
    for key in keys:
        var = SwiftVar()
        if isinstance(dictionary[key], dict):
            var.name = key
            var.type = object.name+"_"+to_camel_case(key)
            
            obj = SwiftObject()
            obj.name = object.name+"_"+to_camel_case(key)

            objects.append((obj, dictionary[key]))
        elif isinstance(dictionary[key], list):
            var.name = key
            var.type = "List"
            if str(printList(dictionary[key])) == "Object":
                var.collection = object.name+"_"+to_camel_case(key)
                
                obj = SwiftObject()
                obj.name = object.name+"_"+to_camel_case(key)
                
                selectBestList(dictionary[key])

                objects.append((obj, selectBestList(dictionary[key])))
            else:
                var.collection = str(printList(dictionary[key]))
        else:
            var.name = key
            var.type = printItem(dictionary[key])
        object.vars.append(var)

def selectBestList(list):
    theItem = list[0]
    for item in list:
        for k, v in item.iteritems():
            if v != None:
                theItem[k] = v
    return theItem
                
def printList(list):
    item = "Any"
    if len(list)!= 0:
        item = printItem(list[0])
    return item

def printItem(item):
    object = "Any"
    if isinstance(item, bool):
        object = "Bool"
    elif isinstance(item, str):
        object = "String"
    elif isinstance(item, unicode):
        object = "String"
    elif isinstance(item, int):
        object= "Int"
    elif isinstance(item, float):
        object = "Float"
    elif isinstance(item, dict):
        object = "Object"
    return object

for obj in objects:
    printDict(obj)

import os
import pwd
import time

def get_username():
    return pwd.getpwuid( os.getuid() )[ 0 ]

file = """//
//  """+sys.argv[2]+""".swift
//
//  File Generated by """+get_username()+""" on """+time.strftime("%m/%d/%Y")+""".
//  Using model_gen.py
//\n
"""
file += "import ObjectMapper\n\n"
for obj in objects:
    swift_obj = obj[0]
    file += swift_obj.printClass()


with open("Smattcom/"+sys.argv[2]+'.swift', 'w') as f:
    f.write(file)

#from pbxproj import XcodeProject
## open the project
#project = XcodeProject.load('Smattcom.xcodeproj/project.pbxproj')
#
#scgroup = project.get_or_create_group('Smattcom')
#apigroup = project.get_or_create_group('API', parent=scgroup)
#group = project.get_or_create_group(sys.argv[2], parent=apigroup)
#
## add a file to it, force=false to not add it if it's already in the project
#project.add_file("Smattcom/"+sys.argv[2]+'.swift', force=False, parent=group)
#
## save the project, otherwise your changes won't be picked up by Xcode
#project.save()

