# -- coding: utf-8 --

#NetP2P Program v0.0.1
#Based on Kademilia

#Created By João Costa, Lukas Mendes, and Jean Lessa
#Licensed By WL
#http://nerdplace.com/lukasmendes/LICENSE-WL.txt

import random
from random import randint
import socket
import hashlib
from wolfcrypt import teste256
import base64
import platform

#tcp = socket.socket(socket.AF_INET. socket.SOCK_STREAM)

DHT_nodes = []

def _logDNS():
    f_dns=open('node_dns.np2p', 'a')
    f_dns.close()

def Sistema():
    f_config=open('config.txt', 'a')
    f_config.truncate()
    os = platform.system()
    cpu = platform.processor()
    if os == 'Windows':
        f_config.write('system "windows"\n')
    elif os == 'Linux':
        f_config.write('system "linux"\n')
    else:
        f_config.write('system "???"\n')
    f_config.write("cpu " + cpu + "\n")
    f_config.close()

def viewTimeout(): #view if the timeout of the network faield
    timeout = 300
    if timeout > timeout-1:
        timeout=timeout-1
        if timeout == 0:
            return False
        return True
    else:
        return False

def sendThing(msg, dest): #send a thing(message) to a node, dest needs to be str(+hash)
    HOST = str(dest)
    PORT = 38
    _dest = (HOST,PORT)
    tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    tcp.connect(_dest)
    tcp.send(msg)

def _generateID(): #Generate a hash for identificate the Node in the network
    _hash = hashlib.sha1()
    _hash.update(str(random.getrandbits(255)))
    return _hash.hexdigest()

def caucularveloc(ping, nodes, dist): #calculates your velocity in the network
    finalveloc = (ping + nodes) / dist
    print('Velocidade : %d mbit/s' % finalveloc)

def gerarip(): #generates a IP in the network
    rand1 = randint(0,256)
    rand2 = randint(0,256)
    rand3 = randint(0,256)
    rand4 = randint(0,256)
    print('IP : ws://%d.%d.%d.%d' % (rand1, rand2, rand3, rand4))

def _sendAddedNode(nameNode): #print for the nodes that's nameNode joined in
    print("%s Has joined(or re-joined) the network" % nameNode)

def encodeVerifyer(data):
    NodeKey = _generateID() + base64.b64encode(data)
    s = NodeKey + base64.b64encode(data)
    return(str(s))

def encode(data):
    return(base64.b64encode(data))

def decode(data):
    return(base64.b64decode(data))

class Node:
    def __init__(self):
        self.state=True
        self.mode="AUS"
        self.id=_generateID()
        self.ip=gerarip()
        self.new=1
        self.serverport=38
        self.clientport=38

node=Node()

def main(): #the final of the show
    print("NetP2P Chat System v0.0 CLOSED ALPHA")
    print("Using WCP protocol")
    print("Connecting...")
    Sistema()
    _logDNS()
    new_node_hash = _generateID()
	
    #putaria
    HOST = 'localhost'
    PORT = 38
    conn = (HOST,PORT)
    #tcp.bind(conn)
    #tcp.connect(conn)

    #tcp.send('?NEWNODE' + " <=> " + new_node_hash)
    start_nodeConnect = 1
    while True:
        if start_nodeConnect > 0:
            _sendAddedNode(new_node_hash)
            DHT_nodes.append(new_node_hash)
            start_nodeConnect = 0
        _data = raw_input('command> ')
        msg = encode(_data)
        if _data == "/help":
            print("NetP2P Network Chat")
            print("v0.0.1 Closed Alpha")
            print("")
            print("Made In Python 2.7, based in kademilia")
            print("")
            print("Commands:")
            print("")
            print("/help => show this help")
            print("/quit or /exit or /q => closes the program")
            print("/whoisme => show your data")
            print("/msg authsys => make your user and password in the system!")
        if _data == "/quit" or _data == "/exit" or _data == "/q":
            node.mode="OFF"
            node.state=False
            print("Quitting...")
            #tcp.close()
            exit(0)
        if _data == "/whoisme":
            gerarnome()
            gerarip()
        if _data == "/faustao":
            node.mode="SEND"
            print("faustao disse : a resposta e holanda")
            #tcp.send("?FAUSTAO PENTELHO")
            node.mode="AUS"
        if _data == "/msg authsys":
            print('NewUser: ')
            _newUser = raw_input()
            print('NewPass: ')
            _newPass = raw_input()
            _newPassEncoded = encodeVerifyer(str(_newPass))
            #tcp.send("?MAKE NEW USER" + _newUser + "?PASS" + _newPassEncoded)
            print('Your New User is: ' + _newUser)
            print("Your Password Encoded is: " + _newPassEncoded)

main()
