#!/usr/bin/python3

from datetime import datetime
import urllib.request
import json
import sys
import os
import shutil
import getpass

username = getpass.getuser()

os.chdir ('/home/' + username + '/.weather-get')

file = open ("location", "r")
country = str(file.readline().rstrip())
city = str(file.readline().rstrip())
file.close()

def check_counter():
	file = open ("counter", "r")
	counter = int(file.readline())
	file.close()
	file = open ("counter", "w")
	if counter > 14400:
		file.write ("0")
		file.close()
		shutil.copy ("history", "backup/history")
		file = open ("log", "w")
		file.write("\n")
		file.close()
		file = open ("history", "w")
		file.write ("\n")
		file.close()
	else:
		file.write (str(counter + 1))
		file.close()	

def check_argument():
	try:
		runtime_argument = sys.argv[1]
		if runtime_argument == "-p":
			file = open ("weather", "r")
			for i in range (1, 11):
				print (file.readline().rstrip())
			file.close()
			return True
	except:
		return False

if check_argument() == True:
	sys.exit()

log_file = open ("log", "a+")
current_time = str(datetime.now())
log_file.write ("weather_get started on " + current_time + "\n")

def check_connectivity():
	try:
		test_connection = urllib.request.urlopen ("http://www.google.com")
		return True
	except:
		return False

	
def file_write():
	file.write (last_update + "\n")
	file.write ("Location    : " + place + "\n")
	file.write ("Observed at : " + observation_location + "\n")
	file.write ("Temperature : " + str(temperature) + "°C\n")
	file.write ("Feels like  : " + str(feels_like) + "°C\n")
	file.write ("Humidity    : " + humidity + "\n")
	file.write ("Condition   : " + current_condition + "\n")
	file.write ("Wind from   : " + wind_direction + " at " + str(wind_speed) + " Kmph\n")
	file.write ("Visibility  : " + visibility + " Km\n")
	file.write ("Forecast    : " + forecast + "\n")


if check_connectivity() == False:
	log_file.write ("network not available\n")
	log_file.write ("exiting...")
	sys.exit()
else:
	log_file.write ("connection established\n")

weather_url = 'http://api.wunderground.com/api/c4ee334a3234caff/geolookup/conditions/forecast/q/' + country + '/' + city + '.json'
weather_api = urllib.request.urlopen (weather_url)
json_input = weather_api.read()
weather_api.close()
json_parsed = json.loads(json_input.decode('utf8'))

place = json_parsed['location']['city']
observation_location = json_parsed['current_observation']['observation_location']['city']
temperature = json_parsed['current_observation']['temp_c']
feels_like = json_parsed['current_observation']['feelslike_c']
humidity = json_parsed['current_observation']['relative_humidity']
current_condition = json_parsed['current_observation']['weather']
wind_direction = json_parsed['current_observation']['wind_dir']
wind_speed = json_parsed['current_observation']['wind_kph']
visibility = json_parsed['current_observation']['visibility_km']
last_update = json_parsed['current_observation']['observation_time']
forecast = json_parsed['forecast']['simpleforecast']['forecastday'][1]['conditions']

file = open ("history", "r")
last_update_history = file.readline()

if last_update + "\n" != last_update_history:
	file.seek (0,0)
	history_file_memory = file.read()
	file.close()
	
	file = open ("history", "w")
	file_write()
	file.write (history_file_memory)
	file.write ("\n")
	log_file.write ("prepending data to history\n")
	file.close()
	
	file = open ("weather", "w")
	file_write()
	log_file.write ("writing current weather information\n")
	file.close()
else:
	log_file.write ("nothing to update\n")

log_file.write ("exiting...\n\n")
log_file.close()

check_counter()
