# Export finite state machines into a text format.
#
# Based on a script by Unai Estebanez Sevilla:
#
#     From: Unai Estebanez <unai unainet net>
#     To: dia-list gnome org
#     Subject: python script to export finite state machines
#     Date: Tue, 7 Jul 2009 15:05:10 +0200
#
#     https://mail.gnome.org/archives/dia-list/2009-July/msg00005.html
#
# Changes by Tomas Pospisek <tpo_deb@sourcepole.ch>
#
# Copyright (c) 2009-2012, Unai Estebanez Sevilla, Tomas Pospisek
#
#   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 2 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, write to the Free Software
#   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.


import dia
import uml_stm_export

class TxtDiagramRenderer(uml_stm_export.SimpleSTM):
    CODE_PREAMBLE = '''
#Machine generated file, do not edit!!!
#Generated by uml_stm_text_export.py script for DIA
#Format is: <comments zone>EOL[STATES]EOL<state>EOL....<state>EOL[TRANSITIONS]EOL<transition>EOL...<transition>EOLEOF
#Where:
#    <comments zone> is a line that begins with \'#\'
#    <state> is a line with comma separated values: state_name,input_action,output_action
#    <transition> is a line with comma separated values: source_state,target_state,trigger,action
#    [STATES] is states zone begin tag
#    [TRANSITIONS] is transitions zone begin tag
#    EOL means End Of Line and EOF means End Of File\n
#-------------------------------------------------------------------------------
'''
    def __init__(self):
        uml_stm_export.SimpleSTM.__init__(self)
        self.filename = ""

    def begin_render (self, data, filename):
        self.filename = filename
        uml_stm_export.SimpleSTM.parse(self, data)
                   
    def end_render(self) :
        f = open(self.filename, "w")
        f.write(self.CODE_PREAMBLE)
        f.write("[STATES]\n")
        for key in self.states.keys():
            state = self.states[key]
            f.write("%s, %s, %s\n" % (state.name, state.iaction, state.oaction))
        f.write("[TRANSITIONS]\n")
        for transition in self.transitions:
            f.write("%s, %s, %s, %s\n" % (transition.source, transition.target, transition.trigger, transition.action))
        f.close()
        self.states = {}
        self.transitions = []


# dia-python keeps a reference to the renderer class and uses it on demand
dia.register_export("State Machine Textual Dump", "txt", TxtDiagramRenderer())
