#!/usr/bin/python
#-*-coding:utf-8-*-

import os
import sys
import json
import base64
import pprint
import xml.etree.ElementTree as ET
import urllib2


def loadJSON( jsonfile ):

    VALUE = {}

    if not os.path.isfile( jsonfile ):
        sys.exit("[ERROR] file(%s) was not found!" % jsonfile)

    f = open( jsonfile, 'r')
    VALUE = json.loads(f.read())
    f.close()
    print ('[INFO] load JSON file - file(%s)' % jsonfile)

    return VALUE




def unicode_to_str(obj):
    """convert unicode object to str"""

    if isinstance(obj, list):
        return [unicode_to_str(element) for element in obj]
    elif isinstance(obj, dict):
        return {unicode_to_str(key) : unicode_to_str(value) for key, value \
                in obj.iteritems()}
    elif isinstance(obj, unicode):
        return obj.encode('utf-8')
    else:
        return obj



def loadXML( url, proxy="ON", error_continue=True ):

    try:
        if( proxy == "OFF" ):

            proxy_handler = urllib2.ProxyHandler({})
            opener = urllib2.build_opener(proxy_handler)
            doc = ET.parse( opener.open(url) )

        else:
            doc = ET.parse( urllib2.urlopen(url).read() )

        root = doc.getroot()

    except urllib2.HTTPError, e:
        print ("[ERROR] HTTP error: %d - %s" % (e.code, url))
        if( error_continue == False ):
            exit(1)
        else:
            return None

    except urllib2.URLError, e:
        print ("[ERROR] Network error: %s - %s" % (e.reason.args[1], url))
        if( error_continue == False ):
            exit(1)
        else:
            return None

    return root






def default(obj):
    import datetime

    if isinstance(obj, datetime.datetime):
        return obj.strftime('%Y-%m-%d %H:%M:%S')

    raise TypeError('Not sure how to serialize %s' % (obj,))


def makeUpdateSQL( table, item, id ):

    set_sql = []

    for k, v in item.items():
        if type(v) == str:
            item[k] = v.replace("'", '"')

        set_sql.append( "`%s` = '%s'" % ( k,str(item[k]) ) )

    result = ','.join(set_sql)

    return ("UPDATE %s SET %s WHERE id = %s" % (table, result, id))




def makeInsertSQL( table, item ):

    for k, v in item.items():
        if type(v) == str:
            item[k] = v.replace("'", '"')

    columns_string = "(`" + "`,`".join(item.keys())+"`)"
    values_string  = "('"  + "','".join(map(str, item.values())) + "')"

    return ("INSERT INTO %s %s VALUES %s" % (table, columns_string, values_string))
