#!/usr/bin/python
import sys
sys.path.append('/home/openlab/mininet/')
from mininet.net import Mininet
from mininet.node import Controller, RemoteController, OVSController
from mininet.node import CPULimitedHost, Host, Node
from mininet.node import OVSKernelSwitch, UserSwitch
from mininet.node import IVSSwitch
from mininet.cli import CLI
from mininet.log import setLogLevel, info
from mininet.link import TCLink, Intf
from subprocess import call
import threading
import time

def myNetwork():
    net = Mininet( topo=None,controller=None,ipBase='10.0.0.0/8')
    
    ## specify clearly to use a remote controller instead of the default one 
    c=RemoteController('c','0.0.0.0',6633)
    net.addController(c)

    info( '*** Add switches\n')
    s1 = net.addSwitch('s1', cls=OVSKernelSwitch,protocols=['OpenFlow13'])
    s2 = net.addSwitch('s2', cls=OVSKernelSwitch,protocols=['OpenFlow13'])
    s3 = net.addSwitch('s3', cls=OVSKernelSwitch,protocols=['OpenFlow13'])
    s4 = net.addSwitch('s4', cls=OVSKernelSwitch,protocols=['OpenFlow13'])
    s5 = net.addSwitch('s5', cls=OVSKernelSwitch,protocols=['OpenFlow13'])
 
    info( '*** Add hosts\n')
    h1 = net.addHost('h1', cls=Host, ip='10.0.0.1', defaultRoute=None,mac='00:00:00:00:00:01')
    h2 = net.addHost('h2', cls=Host, ip='10.0.0.2', defaultRoute=None,mac='00:00:00:00:00:02')

    
    info( '*** Add links\n')
    net.addLink(h1, s1)
    net.addLink(h2, s5)

    net.addLink(s1, s2,bw=10, delay='1ms')
    net.addLink(s1, s4,bw=10, delay='1ms')
    net.addLink(s2, s3,bw=10, delay='1ms')
    net.addLink(s4, s5,bw=10, delay='1ms')
    net.addLink(s3, s5,bw=10, delay='1ms')


    ## start switch
    for i in range(1,6):#6
        net.get("s{}".format(i)).start([])

    info( '*** Starting network\n')
    net.start()

    #into the interactive mode
    def thread1():
        CLI(net)
        net.stop()

    t1 = threading.Thread(target = thread1)
    t1.start()
    def thread2():
        time.sleep(15)
        j=0
        k=3
        net.configLinkStatus('s' + str(int(j+1)),'s' + str(int(k+1)),'down')
        net.configLinkStatus('s' + str(int(2)),'s' + str(int(2+1)),'down')        

    t2 = threading.Thread(target = thread2)
    t2.start()

    def thread3():
        time.sleep(30)
        j=0
        k=3
        net.configLinkStatus('s' + str(int(j+1)),'s' + str(int(k+1)),'up')
        net.configLinkStatus('s' + str(int(2)),'s' + str(int(2+1)),'up')        

    t3 = threading.Thread(target = thread3)
    t3.start()

if __name__ == '__main__':
    setLogLevel( 'info' )
    myNetwork()