from django.core.management.base import BaseCommand, CommandError
from django.utils import timezone
from austria.models import PollingStation, Election, Party, RegionalElectoralDistrict, State, District, Municipality, List
import json
import datetime
import os

class Command(BaseCommand):

	help = 'Import basic data into database'

	def add_arguments(self, parser):
		"""
		Add extra arguments to command.
		"""
		parser.add_argument(
			'path',
			nargs='?',
			help='Specify a different location from where to take the setup data'
		)

	def handle(self, *args, **options):
		"""
		Main entry point of the command.
		"""

		if options['path']:
			setup_path = options['path']
		else:
			setup_path = os.path.dirname(os.path.realpath(__name__)) + '/data/base/'

		config = {
			'party_location': 'austria',
			'log_detail' : 'low'
		}

		# import elections
		elections = self.open_jsonfile(setup_path + 'elections.json')
		self.import_elections(elections, config)

		# import regional electoral districts
		reds = self.open_jsonfile(setup_path + 'regional-electoral-districts_20170101.json')
		self.import_reds(reds, config)

		# import parties
		parties = self.open_jsonfile(setup_path + 'parties.json')
		self.import_parties(parties, config)

		# import lists
		lists = self.open_jsonfile(setup_path + 'lists.json')
		self.import_lists(lists, config)

		# import states and districts
		states_districts = self.open_jsonfile(setup_path + 'states-to-districts_20170101.json')
		self.import_states_districts(states_districts, config)

		# import municipalities
		municipalities = self.open_jsonfile(setup_path + 'municipalities_20170101_2.json')
		muns2reds = self.open_jsonfile(setup_path + 'municipality2red_20170101.json')

		self.import_municipalities(municipalities, muns2reds, config)

	def open_file(self, filename,):
		"""
		Open file.
		"""

		try:
			with open(filename, encoding='utf-8') as data_file:
				return data_file.read()
		except IOError:
			print('Error: can\'t find file or read data')

	def open_jsonfile(self, filename):

		try:
			data = json.loads(open(filename, encoding='utf-8-sig').read())
			return data
		except ValueError:
			print('Error: File is not valid JSON.')

	def import_elections(self, elections, config):
		"""
		Import elections data into database.
		"""

		num_entries_created = 0
		num_entries_updated = 0

		for key, value in elections.items():
			ts = datetime.datetime.strptime(value['election_day'], '%Y-%m-%d')
			ts = timezone.make_aware(ts, timezone.get_current_timezone())

			e = Election.objects.update_or_create(
				short_name = value['short_name'],
				short_name_text = value['short_name_text'],
				full_name = value['full_name'],
				election_type = value['election_type'],
				wikidata_id = value['wikidata_id'],
				administrative_level = value['administrative_level'],
				election_day = ts,
				status = value['status']
			)
			if e[1] == True:
				if config['log_detail'] == 'high':
					print('New election entry "'+value['short_name']+'" created.')
				num_entries_created += 1
			else:
				if config['log_detail'] == 'high':
					print('Election entry "'+value['short_name']+'" updated.')
				num_entries_updated += 1

		print('Election table imported: '+ 'new entries: '+str(num_entries_created)+', updated entries: '+str(num_entries_updated))

	def import_reds(self, reds, config):
		"""
		Import regional electoral districts data into database.
		"""

		num_entries_created = 0
		num_entries_updated = 0

		for key, value in reds.items():
			red = RegionalElectoralDistrict.objects.update_or_create(
				short_code=str(key),
				name = value
			)
			if red[1] == True:
				if config['log_detail'] == 'high':
					print('New regional electoral district entry "'+value+'" created.')
				num_entries_created += 1
			else:
				if config['log_detail'] == 'high':
					print('Regional electoral district entry "'+value+'" updated.')
				num_entries_updated += 1

		print('Regionalelectoraldistrict table imported: '+ 'new entries: '+str(num_entries_created)+', updated entries: '+str(num_entries_updated))

	def import_parties(self, parties, config):
		"""
		Import parties data into database.
		"""

		num_entries_created = 0
		num_entries_updated = 0

		for key, value in parties.items():
			p = Party.objects.update_or_create(
				short_name = value['short_name'],
				short_name_text = value['short_name_text'],
				full_name = value['full_name'],
				family = value['family'],
				wikidata_id = value['wikidata_id'],
				website = value['website'],