import json
from typing import List, Dict
import hashlib

class AgiRepository:
    def getLocations(self) -> List[Dict]:
        locations = []

        travels = self.readDataFromFile()

        # only take started travels
        travels = [t for t in travels if t['status'] >= 2]
        for travel in travels:

            num_complete_travels = min(len(travel['startedBy']), len(travel['users']))
            for i in range(num_complete_travels):

                cur_location = travel['startedBy'][i]
                cur_user = travel['users'][i]

                locations.append(
                    self.location(f'{travel["id"]}-{cur_location["moment"]}',
                            cur_location['coordinate']['latitude'],
                            cur_location['coordinate']['longitude'],
                            cur_location['moment'],
                            # todo user in travel startedBy not available from dataset - currently using user list 
                            hashlib.sha1(cur_user['userId'].encode()).hexdigest() # not showing generated username 
                ))

        return locations

    def getLocationsBasedOnNewDataSchema(self):
        '''Creates the new data generic schema to be used beginning on 24.03.2020'''
        data = {
            'layer_name': 'Destination',
            'nodes': self.getLocations(),
            'properties': ['latitude', 'longitude']
        }
        return data
        
    def getTimesBasedOnNewDataSchema(self):
        '''Creates the new data generic schema to be used beginning on 24.03.2020'''
        data = {
            'layer_name': 'Starting_Time',
            'nodes': self.getLocations(),
            'properties': ['timestamp']
        }
        return data

    def readDataFromFile(self) -> List[Dict]:
        with open('./db/agi/travels.json', 'r') as f_travels:
            travels = json.loads(f_travels.read())

        return travels

    def location(self, id_, lat, long_, timestamp, username) -> dict:
        return {
            "id": id_,
            'latitude': lat,
            'longitude': long_,
            "timestamp": timestamp,
            "user": username
        }

