
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

""" Piaget is a system to geotag historical building photos.
"""

import math
import csv
from operator import itemgetter
import random
import json
from pathlib import Path
import argparse
import uuid
import numpy as np

parser = argparse.ArgumentParser(description="Enter the input JSON configs using the --configs flag.")
required = parser.add_argument_group('required arguments')
required.add_argument("--configs", help="path to the configs json file.", required=True)


class MapFeatures(object):
  def __init__(self, path_to_features_json, years):
    self.years = years
    self.years_dict = {}
    self.data_dict = {}
    self.street_dict = {}
    self.nodes = {}
    self.edges = {}

    self.read_input(path_to_features_json)
    self.create_years_dict()
    self.create_address_dict()
    self.sort_housenumbers()
    self.create_all_nodes()
    self.create_all_edges()

  def read_input(self, path_to_features_json):
    with open(path_to_features_json) as json_file:
      self.raw_data = json.load(json_file)["data"]

  def create_years_dict(self):
    for year in self.years:
      self.years_dict[year] = []
    for feature in self.raw_data:
      if all (key in feature["properties"] for key in ["building","addr:street","addr:housenumber"]):
        self.data_dict[feature["id"]] = feature
        for year in self.years:
          if self.existed_in_year(feature, year):
            self.years_dict[year].append(feature)
          
  def existed_in_year(self, feature, year):
    if "properties" not in feature:
      return True
    # if all (key in feature["properties"] for key in ["start_date","end_date"]):
    if "start_date" not in feature["properties"]:
      if "end_date" not in feature["properties"]:
        return True
      return int(feature["properties"]["end_date"]) > year
    else:
      if int(feature["properties"]["start_date"]) > year:
        return False
      else:
        if "end_date" not in feature["properties"]:
          return True
        return int(feature["properties"]["end_date"]) > year

    return True

  def create_address_dict(self):
    for year in self.years:
      if year not in self.street_dict:
        self.street_dict[year] = {}
      for feature in self.years_dict[year]:
        if feature["properties"]["addr:street"].lower() not in self.street_dict[year]:
          self.street_dict[year][feature["properties"]["addr:street"].lower()] = {"odd":[], "even":[]}
        housenumber = float(feature["properties"]["addr:housenumber"])
        odd_or_even_key = "even" if housenumber % 2 == 0 else "odd"
        self.street_dict[year][feature["properties"]["addr:street"].lower()][odd_or_even_key].append((housenumber, feature["id"]))
  
  def sort_housenumbers(self):
    for year in self.years:
      for street in self.street_dict[year]: