
import mitmProxyAddons

from mitmproxy.tools import _main


import threading
import asyncio

def startProxyAndExec(runtime, sProcessor, sampleLogDir, enableSimulation):
    from mitmproxy import proxy, options
    from mitmproxy.tools.dump import DumpMaster


    opts = options.Options(listen_host='0.0.0.0', listen_port=8080, mode='transparent', confdir='/home/user/.mitmproxy', ssl_insecure=True)
    pconf = proxy.config.ProxyConfig(opts)
    master = DumpMaster(opts)
    master.server = proxy.server.ProxyServer(pconf)

    #create addons
    addons = []

    #Main addons
    addons.append( mitmProxyAddons.TimerAddon(master, runtime) ) #this addon is needed, otherwise mitmProxy will run forever
    if sProcessor.execWithExternalCallback:
        addons.append( mitmProxyAddons.LauncherAddon(sProcessor) ) #this addon is needed to execute sample after mitmProxy started running

    #Simulation addons

    if enableSimulation:
        simAddons = []
        simAddons.append(mitmProxyAddons.RemoteServerSimulation_AZORultVariant1("AZORult_variant1", sampleLogDir))  # make our own responses
        simAddons.append(mitmProxyAddons.RemoteServerSimulation_AZORultVariant2("AZORult_variant2", sampleLogDir))
        simAddons.append(mitmProxyAddons.RemoteServerSimulation_Evrial("Evrial", sampleLogDir))
        simAddons.append(mitmProxyAddons.RemoteServerSimulation_AZORult_3_2("AZORult_3_2", sampleLogDir))
        simAddons.append(mitmProxyAddons.RemoteServerSimulation_AcridRain("AcridRain", sampleLogDir))
        simAddons.append(mitmProxyAddons.RemoteServerSimulation_KpotStealer("KpotStealer", sampleLogDir))

        # add only the needed simulation addons (try to find the name in the path of the sample)
        for simAddon in simAddons:
            if sProcessor.currentSampleLocalFilePath.find(simAddon.name) != -1:
                addons.append(simAddon)
                break

    #print(addons)

    #Logger addons
    addons.append( mitmProxyAddons.TcpLoggerAddon())
    addons.append( mitmProxyAddons.HttpLoggerAddon(sampleLogDir) ) # we can log here own responses, since its after our simulation addons in the addon chain

    addons.append( mitmProxyAddons.DummyAddon() ) #changes request


    #add addons (and automatically registered)
    for addon in addons:
        master.addons.add(addon)


    for addon in master.addons.chain:
        if addon.__class__.__name__ == "ClientPlayback": #threads of RequestReplayThread are not terminating. have to terminate them manually?
            master.addons.remove(addon)
            break



    # run proxy
    try:
        master.run() # this cant be run in a new thread
    except KeyboardInterrupt as e:
        master.shutdown()

    asyncio.set_event_loop(asyncio.new_event_loop())


