#!/usr/bin/python

## Copyright 2013 A Mennucc1
##
##  This file is part of wfrog
##  It converts CSV recordings of meteo data to Sqlite3
##
##
##  wfrog is free software: you can redistribute it and/or modify
##  it under the terms of the GNU General Public License as published by
##  the Free Software Foundation, either version 3 of the License, or
##  (at your option) any later version.
##
##  This program is distributed in the hope that it will be useful,
##  but WITHOUT ANY WARRANTY; without even the implied warranty of
##  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
##  GNU General Public License for more details.
##
##  You should have received a copy of the GNU General Public License
##  along with this program.  If not, see <http://www.gnu.org/licenses/>.


import csv, time, string, os, sys, sqlite3
import os.path
from datetime import datetime


if len(sys.argv) != 3:
	print """
Usage: csv2sql input.csv output.sql

This program reads CSV recordings of meteo data, and adds them to a Sqlite3
database. The database must be initialized to contain the table 'METEO',
see database/sqlite3.sql in the source code.
Note that the SQL table it may contain more fields per record than the CSV;
this script will selfadapt.
"""
	sys.exit(0)

columns = [ 'timestamp', 'localtime', 'temp', 'hum', 'wind', 'wind_dir', 'wind_gust', 'wind_gust_dir', 'dew_point', 'rain', 'rain_rate', 'pressure', 'uv_index' ]

def _get_table_fields(db, tablename='METEO'):
        sql = "PRAGMA table_info(%s);" % tablename
        fields = []

        c=db.cursor()
        c.execute(sql)
        for row in c:
            fields.append(row[1].lower())

        return fields

reader = csv.reader(open(sys.argv[1]))
writer = sqlite3.connect(sys.argv[2],  detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)

table_fields = _get_table_fields(writer)
# Verify Mandatory fields
assert 'timestamp_utc' in table_fields
assert 'timestamp_local' in table_fields

inserter='?,'*len(table_fields)
inserter="insert into METEO  values ( %s ) ;" % inserter[:-1]

themap=[]
for i in range(len(table_fields)):
    try:
        j=columns.index(table_fields[i])
        themap.append(j)
    except ValueError:
        themap.append(None)
themap[0]=1
themap[1]=1

c=writer.cursor()
for l in reader:
    if not l:
        continue
    w=[]
    for i in range(len(table_fields)):
        if themap[i] != None:
            v=l[themap[i]]
            if len(v)==0:
                w.append(None)
            else:
                w.append(v)
        else:
            w.append(None)
    c.execute(inserter, w)
writer.commit()
c.close()
