#!/usr/bin/env python
"""
plugins.unusual_light_curve

MOPS Alert Rule that returns DerivedObjects for which either one is true:
    1. the difference in magnitude between detections in any given tracklet
       is > 0.3 mag.
    2. the min-max magnitude amongst all detections is > 1.0 mag.
"""

from base import DerivedObjectRule
from MOPS.Alerts.plugins.Constants import CH_LIGHT
import sys



class UnusualLightCurves(DerivedObjectRule):
    """
    Return all new or newly modified DerivedObject instances.
    """
    def isUnusual(self, obj):
        """
        Return True if either one is true for obj:
        1. the difference in magnitude between detections in any given tracklet
           is > 0.3 mag.
        2. the min-max magnitude amongst all detections is > 1.0 mag.

        @param obj: DerivedObject instance
        """
        tracklets = obj.alertObj.tracklets

        # First, check rule number 1.
        allMags = []
        for t in tracklets:
            mags = [d.mag for d in t.detections]
            mags.sort()
            if(abs(mags[-1] - mags[0]) > 0.3):
                return(True)
            # <-- end if

            # That was not True, update allMags just in case we have to test
            # rule 2 as well.
            allMags += mags
        # <-- end for
        
        # Then rule number 2.
        allMags.sort()
        return(abs(allMags[-1] - allMags[0]) > 1.)

    
    def evaluate(self):
        """
        Return a list of DerivedObject instances that satisfy the rule.
        """
        #Set the channel that will be used to publish the alert.
        self.channel = CH_LIGHT
        return([obj for obj in self.newAlerts if self.isUnusual(obj)])
# <-- end class

def main(args=sys.argv[1:]):
    rule = UnusualLightCurves()
    alerts = rule.evaluate()
    
    for alert in alerts:
        print(str(alert) + '\n\n')
# <-- end main    

if(__name__ == '__main__'):
    sys.exit(main())
# <-- end if