#!/usr/bin/env python
# -*- coding:utf-8 -*- 

__author__="Sylvain LAFRASSE"
__date__ ="$21 oct. 2015 16:38:14$"

"""
Copyright (c) 2015, CNRS. All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    - Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    - Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    - Neither the name of the CNRS nor the names of its contributors may be
      used to endorse or promote products derived from this software without
      specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL CNRS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--------------------------------------------------------------------------------
ExTrA module to wrap ScopeDome ASCOM interface.
"""

import datetime
import time
import sys
import math
import Queue

from xtlpy import comthread
from xtlpy import logger

from enum import Enum, unique
@unique
class RELAY(Enum):
    SCOPE = ("Rel_Scope_", "Rel_Scope_")
    CCD   = ("Rel_CCD_",   "Rel_CCD_")
    LIGHT = ("Rel_Light_", "Rel_Light_")
    FAN   = ("Rel_Fan_",   "Rel_Fan_")
    ONE   = ("Rel_REL_1_", "Rel_1_")
    TWO   = ("Rel_REL_2_", "Rel_2_")
    THREE = ("Rel_REL_3_", "Rel_3_")
    FOUR  = ("Rel_REL_4_", "Rel_4_")

@unique
class SHUTTER(Enum):
    # shutterOpen    0   Dome shutter status open
    OPEN    = 0
    # shutterClosed  1   Dome shutter status closed
    CLOSED  = 1
    # shutterOpening 2   Dome shutter status opening
    OPENING = 2
    # shutterClosing 3   Dome shutter status closing
    CLOSING = 3
    # shutterError   4   Dome shutter status error
    ERROR   = 4

class ScopeDomeWrapper():
    """
    This class wraps ScopeDome ASCOM interface to simplify calling code.
    """

    def __init__(self):
        self.__comThread = None
        self.__logger = logger.createLogger(__name__)
        self.__comThreadFailureQueue = Queue.Queue()

    def getFailureQueue(self):
        return self.__comThreadFailureQueue

    def connect(self, sim_flag=False):
        # Create new thread if needed
        if self.__comThread == None:
            self.__comThread = comthread.ComThread("ASCOM.ScopeDomeUSBDome.DomeLS", self.__comThreadFailureQueue, sim_flag)
            self.__comThread.start()
            time.sleep(5)

    def showSetupDialog(self):
        print "Getting 'SupportedActions':"
        print self.__comThread.waitForPropertyRead("SupportedActions")
        # print "SetupDialog : ",
        self.__comThread.waitForMethodExecution("SetupDialog")
        # TODO : Must restart driver !!!

    def goHome(self):
        self.enableSkySync(False)
        if not self.isAtHome():
            self.findHome()

    def isHardwareConnexionOk(self):
        """
        Return True if hardware connexion is ok, False otherwise.
        """
        if self.__comThread.waitIntForStringCommand("Dome_Error") == 0:
            return True
        return False

    def isCloudSensorActive(self):
        """
        Return True if the Cloud Sensor input is activated, False otherwise.
        """
        return bool(self.__comThread.waitIntForStringCommand("Internal_Sensor_Clouds"))

    def getInsideTemperature(self):
        return self.__comThread.waitFloatForStringCommand("Temperature_In_Dome")

    def getOutsideTemperature(self):
        return self.__comThread.waitFloatForStringCommand("Temperature_Outside_Dome")

    def getDewPoint(self):
        return self.__comThread.waitFloatForStringCommand("Dew_Point")

    def getHumidity(self):
        return self.__comThread.waitFloatForStringCommand("Humidity_Humidity_Sensor")

    def getHumidityTemperature(self):
        return self.__comThread.waitFloatForStringCommand("Temperature_Humidity_Sensor")

    def getPressure(self):
        return self.__comThread.waitFloatForStringCommand("Pressure")

    def getAzimuth(self):
        try:
            result = self.__comThread.waitForPropertyRead("Azimuth")
            return float(result)
        except ValueError:
            self.__logger.warning("Could not convert '" + result + "' azimuth to float.")
            return float('nan')

    def abort(self):
        print "ASCOM AbortSlew : ", self.__comThread.waitForMethodExecution("AbortSlew", ())
        print "ScopeDome Stop : ", self.__comThread.waitForStringCommand("Stop")
        # TODO : raise exception if problem

    def slewToAzimuth(self, az):
        assert isinstance(az, (int, long, float))
        print "SlewToAzimuth(" , az, ") : ", self.__comThread.waitForMethodExecution("SlewToAzimuth", (az,))
        self.waitStop(az)
        # TODO : raise exception if destination not reached (what delta ?)

    def getEncoderCounter(self):
        # WARN : ScopeDome typo and inversion with "Internal_Sensor_Dome_Encoder_Counter" in patched code command string !
        return self.__comThread.waitIntForStringCommand("Internal_Sensor_Dome_Roatate_Counter")

    def encGoTo(self, step):
        assert isinstance(step, (int, long))
        print "Enc_GoTo(", step, ") : ", self.__comThread.waitForStringCommand("Enc_GoTo " + str(step))
        self.waitStop()
        # TODO : raise exception if destination not reached (what delta ?)

    def openShutter(self):
        # TODO : check global security flag before opening !!!
        print datetime.datetime.now(), "OpenShutter : ", self.__comThread.waitForMethodExecution("OpenShutter")
        self.waitStop()

    def closeShutter(self):
        print datetime.datetime.now(), "CloseShutter : ", self.__comThread.waitForMethodExecution("CloseShutter")
        self.waitStop()

    def asyncOpenShutter(self):
        # TODO : check global security flag before opening !!!
        print datetime.datetime.now(), "ASYNC OpenShutter : ", self.__comThread.asyncMethodExecution("OpenShutter")
        self.waitStop()

    def asyncCloseShutter(self):
        print datetime.datetime.now(), "ASYNC CloseShutter : ", self.__comThread.asyncMethodExecution("CloseShutter")
        self.waitStop()

    def getShutterStatus(self):
        # shutterOpen    0   Dome shutter status open
        # shutterClosed  1   Dome shutter status closed
        # shutterOpening 2   Dome shutter status opening
        # shutterClosing 3   Dome shutter status closing
        # shutterError   4   Dome shutter status error
        status = self.__comThread.waitForPropertyRead("ShutterStatus")
        state = SHUTTER(status)
        #print datetime.datetime.now(), "ShutterStatus : ", state
        return state

    def enableSkySync(self, flag):
        assert isinstance(flag, bool)
        if flag == True:
            print "Sky_Sync 1 : ", self.__comThread.waitForStringCommand("Sky_Sync 1")
        else:
            print "Sky_Sync 0 : ", self.__comThread.waitForStringCommand("Sky_Sync 0")

    def findHome(self):
        while not self.goBackHome():
            if not self.calibrateHome():
                print "On est dans la MERDE !!!"
        # TODO : raise exception if destination not reached (what delta ?)

    def isAtHome(self):
        #return self.waitRadio()
        return int(self.__comThread.waitForStringCommand("Internal_Sensor_Dome_At_Home"))

    def getRadioSignalStength(self):
        radioStregth = self.__comThread.waitIntForStringCommand("Shutter_Link_Strength")
        if math.isnan(radioStregth):
            print "SIMULATION"
            return 100
        return radioStregth

    def getRelayState(self, relay):
        assert isinstance(relay, RELAY)
        return bool(self.__comThread.waitIntForStringCommand(relay.value[0] + "Get_State"))

    def setRelayState(self, relay, state):
        assert isinstance(relay, RELAY)
        assert isinstance(state, bool)
        if state == True:
            print "Turning relay '" + relay.name + "' ON : ", self.__comThread.waitForStringCommand(relay.value[1] + "ON")
        else:
            print "Turning relay '" + relay.name + "' OFF : ", self.__comThread.waitForStringCommand(relay.value[1] + "OFF")

    def waitRadio(self):
        print "Waiting for RADIO signal :"
        radio = self.getRadioSignalStength()
        # print "\tFlushing previous value = ", radio
        time.sleep(3)
        nbTests = 10
        print "\t",
        for retries in range(nbTests):
            radio = self.getRadioSignalStength()
            if radio > 0:
                print "signal found (", radio, ")."
                return True
            elif (retries == nbTests - 1):
                print "signal NOT found."
            else:
                sys.stdout.write('.')
                time.sleep(2)
        return False

    def goBackHome(self):
        print datetime.datetime.now(), " ---> GO BACK HOME !!!"

        # First try with ScopeDome provided function
        print datetime.datetime.now(), "Dome_Find_Home : ", self.__comThread.waitForStringCommand("Dome_Find_Home")
        self.waitStop() # wait for home sensor triggering
        self.waitStop() # wait for GotoAz 0
        self.waitStop() # wait for GotoEnc 0

        atHome =  self.isAtHome()
        print "atHome =", atHome
        # If home not found, try with our own algorithm
        if not atHome:
            print datetime.datetime.now(), "Dome_Derotate : ", self.derotate()
            self.waitStop()
            self.slewToAzimuth(15) # degrees
            self.encGoTo(0)

        print "AtPark = %s" % (self.__comThread.waitForPropertyRead("AtPark"))
        print "Azimuth = %s" % (self.__comThread.waitForPropertyRead("Azimuth"))
        atHome =  self.isAtHome()
        print "atHome =", atHome
        return atHome

    def calibrateHome(self):
        print datetime.datetime.now(), " ---> CALIBRATE HOME !!!"
        self.encGoTo(0)
        zeroEncAz = self.getAzimuth()
        print "zeroEncAz = ", zeroEncAz

        # TODO : Get this value from outside !!!
        stepByTurn = 4584
        approxZeroEnc = int((zeroEncAz / 360.0) * stepByTurn) % stepByTurn
        print "approxZeroEnc = ", approxZeroEnc

        totalHomeSteps = 0
        nbHomeSteps = 0
        for i in range(approxZeroEnc - 10, approxZeroEnc + 10 + stepByTurn): # Az est bon +/- 1 degree, soit +/- 12.7 pas -> on arrondi a 10
            self.encGoTo(i)
            if self.isAtHome():
                totalHomeSteps += i
                nbHomeSteps += 1
            elif (nbHomeSteps > 0):
                print "\tIN and OUT home steps FOUND, aborting bruteforce search !"
                break
            print

        if nbHomeSteps > 0:
            meanHomeStep = totalHomeSteps / nbHomeSteps
            print "Fine checking home step around detected encoder position ", meanHomeStep," (+/-1) :"
            lst = (meanHomeStep, meanHomeStep - 1, meanHomeStep + 1)
            for i in lst:
                self.encGoTo(i)
                if self.isAtHome():
                    print datetime.datetime.now(), "Reseting Az Encoder:", self.resetAzimuthEncoder()
                    print datetime.datetime.now(), "Reseting Rotate Encoder:", self.resetEncoderCounter()
                    return True

        print datetime.datetime.now(), "Calibration FAILLURE !!!"
        # TODO : start internal calibration ???
        return False

    def resetAzimuthEncoder(self):
        print "ScopeDome Reset_Dome_Az_Encoder : ", self.__comThread.waitForStringCommand("Reset_Dome_Az_Encoder")
        # TODO : raise exception if problem

    def resetEncoderCounter(self):
        print "ScopeDome Reset_Dome_Rotate_Encoder : ", self.__comThread.waitForStringCommand("Reset_Dome_Rotate_Encoder")
        # TODO : raise exception if problem

    def derotate(self):
        print "ScopeDome Dome_Derotate : ", self.__comThread.waitForStringCommand("Dome_Derotate")
        # TODO : raise exception if problem

    def calibrateAzimuthEncoder(self):
        print "ScopeDome Calibrate_Dome_Az_Encoder : ", self.__comThread.waitForStringCommand("Calibrate_Dome_Az_Encoder")
        # TODO : raise exception if problem

    def calibrateInertia(self):
        print "ScopeDome Calibrate_Dome_Inertia : ", self.__comThread.waitForStringCommand("Calibrate_Dome_Inertia")
        # TODO : raise exception if problem

    def restoreDefault(self):
        print "ScopeDome Restore_Default : ", self.__comThread.waitForStringCommand("Restore_Default")
        # TODO : raise exception if problem

    def waitStop(self, goal = 0.0):
        assert isinstance(goal, (int, long, float))
        seconds = 0
        time.sleep(2)
        print "\tSlewing : ",

        slewing = True
        while (slewing):
            slewing = self.__comThread.waitForPropertyRead("Slewing")
            if math.isnan(float(slewing)):
                print " SIMULATION"
                return 0
            sys.stdout.write('.')
            time.sleep(1)
            seconds += 1

        time.sleep(2)
        print " Done"
        delta = (goal - self.getAzimuth())
        print "\tDelta = ", delta
        print "\tSeconds = ", seconds
        return delta

    def exit(self):
        print "EXIT : ", self.__comThread.waitForExit()
        print "Exiting ASCOM Thread."
