# -*- coding: utf-8 -*-

#+---------------------------------------------------------------------------+
#|          01001110 01100101 01110100 01111010 01101111 01100010            |
#|                                                                           |
#|               Netzob : Inferring communication protocols                  |
#+---------------------------------------------------------------------------+
#| Copyright (C) 2011 Georges Bossert and Frédéric Guihéry                   |
#| This program is free software: you can redistribute it and/or modify      |
#| it under the terms of the GNU General Public License as published by      |
#| the Free Software Foundation, either version 3 of the License, or         |
#| (at your option) any later version.                                       |
#|                                                                           |
#| This program is distributed in the hope that it will be useful,           |
#| but WITHOUT ANY WARRANTY; without even the implied warranty of            |
#| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the              |
#| GNU General Public License for more details.                              |
#|                                                                           |
#| You should have received a copy of the GNU General Public License         |
#| along with this program. If not, see <http://www.gnu.org/licenses/>.      |
#+---------------------------------------------------------------------------+
#| @url      : http://www.netzob.org                                         |
#| @contact  : contact@netzob.org                                            |
#| @sponsors : Amossys, http://www.amossys.fr                                |
#|             Supélec, http://www.rennes.supelec.fr/ren/rd/cidre/           |
#+---------------------------------------------------------------------------+

#+---------------------------------------------------------------------------+
#| Standard library imports
#+---------------------------------------------------------------------------+
from gettext import gettext as _
import logging
import random
import time


#+---------------------------------------------------------------------------+
#| Related third party imports
#+---------------------------------------------------------------------------+
from lxml.etree import ElementTree

#+---------------------------------------------------------------------------+
#| Local application imports
#+---------------------------------------------------------------------------+
from netzob.Common.MMSTD.Transitions.AbstractTransition import AbstractTransition
from netzob.Common.MMSTD.Symbols.impl.EmptySymbol import EmptySymbol
from netzob.Common.MMSTD.Symbols.impl.UnknownSymbol import UnknownSymbol
from netzob.Common.MMSTD.Symbols.impl.DictionarySymbol import DictionarySymbol
from lxml import etree


#+---------------------------------------------------------------------------+
#| SemiStochasticTransition:
#|     Definition of a semi stochastic transition
#+---------------------------------------------------------------------------+
class SemiStochasticTransition(AbstractTransition):

    TYPE = "SemiStochastic"

    def __init__(self, id, name, inputState, outputState, inputSymbol):
        AbstractTransition.__init__(self, SemiStochasticTransition.TYPE, id, name, inputState, outputState)
        # create logger with the given configuration
        self.log = logging.getLogger('netzob.Common.MMSTD.Transitions.impl.SemiStochasticTransition.py')
        self.inputSymbol = inputSymbol
        # Output Symbols : [[Symbol, Probability, Time], [Symbol, Probability, Time]]
        self.outputSymbols = []

    #+-----------------------------------------------------------------------+
    #| getOutputSymbols
    #|     Return the associated output symbols
    #| @return the outputSymbols ([[Symbol, Probability, Time], [Symbol, Probability, Time]])
    #+-----------------------------------------------------------------------+
    def getOutputSymbols(self):
        return self.outputSymbols

    #+-----------------------------------------------------------------------+
    #| getInputSymbol
    #|     Return the associated oinput symbol
    #| @return the input symbol
    #+-----------------------------------------------------------------------+
    def getInputSymbol(self):
        return self.inputSymbol

    #+-----------------------------------------------------------------------+
    #| addOutputSymbol
    #|     Add an output symbol to the current transition
    #| @param outputsymbol the symbol to add
    #| @param probability the associated probability (<100)
    #| @param time the necessary time for this symbol
    #| @return the outputSymbols
    #+-----------------------------------------------------------------------+
    def addOutputSymbol(self, outputSymbol, probability, time):
        self.outputSymbols.append([output
Symbol, probability, time])

    #+-----------------------------------------------------------------------+
    #| isValid
    #|     Computes if the recei
ved symbol is valid
    #| @return a boolean which indicates if received symbol is equivalent
    #+-----------------------------------------------------------------------+
    def isValid(self, receivedSymbol):
        return self.inputSymbol.getID() == receivedSymbol.getID()

    #+-----------------------------------------------------------------------+
    #| pickOutputSymbol
    #|     Randomly select an output symbol
    #| @return the randomly picked output symbol [symbol, proba, time]
    #+-----------------------------------------------------------------------+
    def pickOutputSymbol(self):
        r = random.randrange(0, len(self.outputSymbols))
        return self.outputSymbols[r]

    #+-----------------------------------------------------------------------+
    #| setProbabilityForOutputSymbol
    #|     Change the value of the probability for a provided output symbol
    #+-----------------------------------------------------------------------+
    def setProbabilityForOutputSymbol(self, outputSymbol, newProbability):
        savedSymbols = []

        for (oldSymbol, oldProba, oldTime) in self.getOutputSymbols():
            if oldSymbol == outputSymbol:
                savedSymbols.append([oldSymbol, newProbability, oldTime])
            else:
                savedSymbols.append([oldSymbol, oldProba, oldTime])

        self.outputSymbols = []
        self.outputSymbols.extend(savedSymbols)

    #+-----------------------------------------------------------------------+
    #| setTimeForOutputSymbol
    #|     Change the value of the time for a provided output symbol
    #+-----------------------------------------------------------------------+
    def setTimeForOutputSymbol(self, outputSymbol, newTime):
        savedSymbols = []

        for (oldSymbol, oldProba, oldTime) in self.getOutputSymbols():
            if oldSymbol == outputSymbol:
                savedSymbols.append([oldSymbol, oldProba, newTime])
            else:
                savedSymbols.append([oldSymbol, oldProba, oldTime])

        self.outputSymbols = []
        self.outputSymbols.extend(savedSymbols)

    #+-----------------------------------------------------------------------+
    #| executeAsClient
    #|     Randomly pick an outputSymbol and send it
    #| @param abstractionLayer the abstract layer to contact in order to reach outside world
    #| @return the new state
    #+-----------------------------------------------------------------------+
    def executeAsClient(self, abstractionLayer):
        self.activate()
        self.log.debug("Executing transition " + self.name + " with input : " + str(self.inputSymbol))
        if (len(self.outputSymbols) > 0):
            [outputSymbol, probability, reactionTime] = self.pickOutputSymbol()

            # before sending it we simulate the reaction time
            time.sleep(int(reactionTime) / 1000)

            abstractionLayer.writeSymbol(outputSymbol)
        self.deactivate()
        return self.outputState

    #+-------------------------