import numpy as np
import networkx as nx
import pickle as pkl
from datetime import datetime


filepath="email-Eu-core-temporal.txt"
outputname="email-eu-core"

g = nx.MultiGraph()

with open(filepath, 'r') as f:
	for line in f.readlines():
		tokens = line.strip().split()
		t = datetime.fromtimestamp(int(tokens[2]))
		secs = (t-datetime(1970,1,1)).total_seconds()
		
		if secs < 0:
			raise ValueError(f"Choose another initial time! {t}")
		g.add_edge(int(tokens[0]), int(tokens[1]), weight=secs)
		
			
nodes_num = g.number_of_nodes()
edges_num = g.number_of_edges()

print(f"Nodes num: {nodes_num}")		
print(f"Edges num: {edges_num}")

# Check if the network is connected
if nx.is_connected(g):
	print("Graph is connected!")


# Relabel nodes
mapping = {node: idx for idx, node in enumerate(g.nodes())}
g = nx.relabel_nodes(G=g, mapping=mapping)

pairs = []
events = []
for i in range(nodes_num):
	for j in g[i]:
		if j > i:
			pairs.append([i, j])
			events.append( [val['weight'] for val in g[i][j].values()] )


with open("./pairs.pkl", 'wb') as f:
	pkl.dump(pairs, f)
with open("./events.pkl", 'wb') as f:
	pkl.dump(events, f)
# Gml file
nx.write_gml(G=g, path="./"+outputname+".gml")
'''

'''