#!/usr/bin/env python
#
# ALMA - Atacama Large Millimeter Array
# (c) Associated Universities Inc., 2015
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA

from threading import Thread
import time
from Acspy.Clients.SimpleClient import PySimpleClient
from ACS import MasterComponent
from ACS import SUBSYSSTATE_AVAILABLE, SUBSYSSTATE_OFFLINE, SUBSYSSTATE_SHUTDOWN, SUBSYSSTATE_ONLINE, SUBSYSSTATE_OPERATIONAL, SUBSYSSTATE_PREINITIALIZED, SUBSYSSTATE_PRESHUTDOWN, SUBSYSSTATE_ERROR


class Startup_test():
    '''
    Utility class to handle subsystem states 
    '''

    def __init__(self, ):
        '''
        Specify which subsystems to start. 
        '''
        # Initialize subsystem master references
        self.client = PySimpleClient()
        self.cont_master = None

        # Initialize Control threads
        self.contStartThread = None
        self.contShuttThread = None

        # Initialize overall startup state
        self.startupState = False


    def startup(self):
        '''
        Start up all subsystems, unless already started by another client.
        '''
        if (not self.startupState):
            if ( self._startCont() ):
                self.startupState = True
            else:
                return False
        return True

    def shutdown(self):
        '''
        Shut down all subsystems.
        '''
        if (self.startupState):
            self._shutdownCont()
            self.startupState = False


### MAster Start ###
    def _startCont(self):
        self.cont_master = self.client.getComponent('TESTMASTERCOMP')
        self.contStartThread = None
        if (self.cont_master._get_componentState() =="UNKNOWN"):
            self.cont_master.startupPass1()
            self.contStartThread = Thread(target=self.cont_master.startupPass2, args=())
            self.controlStartThread.start()
            return True
    
    def _shutdownControl(self):
        if (self.cont_master is None): return

        cont_state = self.cont_master.getMasterState()
        if (cont_state == OPERATIONAL):
            self.conthuttThread = Thread(target=self.cont_master.shutdownPass1, args=())
            self.contShuttThread.start()
    
    def _joinShutdownControl(self):
        if (self.controlShuttThread is not None):
            self.controlShuttThread.join()
            self.controlShuttThread = None

            self.cont_master.shutdownPass2()
            self.client.releaseComponent(self.cont_master._get_name())
            self.cont_master = None

# **************************************************
# MAIN Program
# **************************************************
if __name__ == '__main__':
    '''
    Use this to startup manually, or as an example for your test script.
    '''
    # Get the handler
    stateHandler = Startup_test()
    
    # Startup
    if ( not stateHandler.startup() ):
        exit(1)
    
    # Wait for shutdown signal
    raw_input("Hit any key to shutdown")
    
    # Shutdown
    stateHandler.shutdown()

