# L-25 MCS 275 Wed 8 Mar 2017 : filldb.py
"""
Script to fill a data base, using pymysql
"""
# import MySQLdb
import os
import pymysql
from grabpyhead import enum_fields

def my_date(data):
    """
    Converts a string such as Wed 9 Mar 2016
    into the format 2016-03-09.
    """
    months = {"Jan":"01", "Feb":"02", "Mar":"03", \
       "Apr":"04", "May":"05", "Jun":"06", \
       "Jul":"07", "Aug":"08", "Sep":"09", \
       "Oct":"10", "Nov":"11", "Dec":"12"}
    vals = data.split(' ')
    day = '%02d' % int(vals[1])
    return vals[3] + '-' + months[vals[2]] + '-' + day

def insert_data(cur, doit=False):
    """
    Data is inserted into the database,
    using the cursor cur.
    """
    def insert(data):
        """
        Uses the tuple data to insert into
        the table scripts.
        """
        cmd = 'insert into scripts values (' \
            + '\"' + data[0] + '\"' + ',' \
            + '\"' + data[1] + '\"' + ',' \
            + '\"' + my_date(data[2]) + '\"' + ',' \
            + '\"' + data[3] + '\"' + ');'
        print('executing', cmd)
        cur.execute(cmd)

    if doit:
        nbr = enum_fields('.', insert)
    else:
        nbr = enum_fields('.', print)
    return nbr

def main():
    """
    Prints the header of all .py files
    in the current directory.
    """
    pth = os.getcwd()
    os.chdir('../MCS275py')
    # db = MySQLdb.connect(db="OurPyFiles")
    ourdb = pymysql.connect(db="OurPyFiles")
    crs = ourdb.cursor()
    ans = input("really do it ? (y/n) ")
    nbr = insert_data(crs, ans == 'y')
    ourdb.commit()
    print('inserted %d .py files' % nbr)
    os.chdir(pth)

if __name__ == "__main__":
    main()
