import sqlite3
import codecs
from ftplib import FTP

f = open('./airplanes_G.html', 'w')

con = sqlite3.connect(r'../virtualRadar.sqb',
	detect_types=sqlite3.PARSE_DECLTYPES | 
	sqlite3.PARSE_COLNAMES)

cur = con.cursor()

#cur.execute('SELECT COUNT(*) from Aircraft')
#cur_result = cur.fetchone()
#print(cur_result)

#cur.execute('SELECT COUNT(*) from Flights')
#cur_result = cur.fetchone()
#rows = cur_result[0]
#print(rows)
#this_year = datetime.date(datetime.date.today().isocalendar()[0], 1, 1)
#this_year = datetime.date(datetime.date.today().isocalendar()[0], 1, 1)
#this_year = (DT.date(DT.date.today().isocalendar()[0], 1, 1))
#print(this_year)

#currentDateTime = datetime.datetime.now()
#print(currentDateTime)

sql = "select Flights.StartTime, Flights.Callsign, Aircraft.Registration, Aircraft.ICAOTypeCode , Aircraft.Type, Aircraft.RegisteredOwners, Aircraft.YearBuilt from Flights INNER JOIN Aircraft on Flights.AircraftID = Aircraft.AircraftID where Flights.Callsign like 'DCM%' group by Registration order by Flights.StartTime DESC"
#sql = 'select Flights.StartTime, Flights.Callsign, Aircraft.Registration, Aircraft.ICAOTypeCode, Aircraft.Type, Aircraft.RegisteredOwners, Aircraft.YearBuilt from Flights INNER JOIN Aircraft on Flights.AircraftID = Aircraft.AircraftID group by Registration'
# WHERE  StartTime BETWEEN JulianDay(\'now\') AND JulianDay(\'now\',\'+1 day\',\'-0.001 second\') 
cur.execute(sql)
cur_result = cur.fetchall()

#cur_result = cur.fetchone()
#row = cur_result[0]
#print(row)
#row = cur.fetchall()

# the html code which will go in the file airplanes.html
html_head = """
<html>
<head><title>Airplane Info 1.0</title>
<style>
a {
  color: black;
  text-decoration: none;
}
</style>
</head>
<body>
<br><br>
<table name="airplanes" id="airplanes" width="88%" border="0">
<tr><th>REG</th><th>CS</th><th nowrap>A Type</th><th>DATE</th><th>INFO</th><th>OWNER</th><th>M YEAR</th></tr>
"""

html_foot = """
</table>  
</body>
</html>
"""


f.write(html_head)

for row in cur_result:
	#print("ID ", row[0], "Reg ", row[1] )
	callsign=str(row[2])
	callsign=callsign.strip("-")
	mylink = '<tr><td><a href="https://flightaware.com/resources/registration/' + callsign + '" target="_new">' + str(row[2]) + '</a></td><td>' + str(row[1]) + '</td><td>' + str(row[3]) + '</td><td nowrap>' + str(row[0]) + '</td><td nowrap style=" padding-left: 20px;">' + str(row[4]) + '</td><td nowrap>' + str(row[5]) + '</td><td nowrap>' + str(row[6]) + '</td></tr>'
	f.write(str(mylink))
    #assert row[0] == row["Reg"]
    #assert row["name"] == row["nAmE"]
    #assert row[1] == row["age"]
    #assert row[1] == row["AgE"]

f.write(html_foot)
f.close()
con.close()