
import os
import twc
import twc.products
import twccommon
import wxscan.dataUtil as dataUtil
import twc.dsmarshal as dsm


class Cosponsor(twc.products.Product):
    def __init__(self, params):
        twc.products.Product.__init__(self, params)

        # set image root
        TWCPERSDIR = os.environ['TWCPERSDIR']

        # Set the behavior for the file validation
        self._startTimeNdx = -3 # Third field from the end
        self._endTimeNdx = -2 # Second field from the end

        # this is where the co-sponsor audio lives
        self._cosponsorRoot = TWCPERSDIR + '/data/volatile/cosponsor/'


    def _loadData(self):
        params = twccommon.DefaultedData(self.getParams())
        data   = self.getData()

        # If max files in rotation has not been configed
        if(params.maxCosponsors is None):
            params.maxCosponsors = 1

        # Assume there is no data
        data.noDataAvailable = 1

        # Get the state from the last time this product ran.
        # NOTE: Because these are currently scheduled on a national basis,
        # all instances will share the same rotation.
        key = '%s.%s.data' % (params.package, params.product)
        nvdata = dsm.defaultedGet(key)

        if nvdata is None:
            # default for 1st time
            nvdata = twc.Data(count=0)

        # see if we have any audio files scheduled to air at this time:
        # sort on valid time (3rd field from last) with the most recent file first
        # This will return a list of tuples [(indexVal, filename), ...]
        audiofileList = dataUtil.getValidFileList(self._cosponsorRoot, params.package, 'wav',
                                             self._startTimeNdx,
                                             self._endTimeNdx,
                                             self._startTimeNdx)

        # We must have a tif and wav in order to consider the sponsor valid.
        validfileList = []
        for unused, audiofileName in audiofileList:
            # Now see if we have a matching TIFF image
            imagefileName = audiofileName[:-3] + 'tif'
            if os.path.isfile(imageFileName):
                validfileList.append(audiofileName[:-4])

        # Per the requirements, restrict the number in the rotation
        # Be sure to do this after we make sure both parts are present
        validfileList = validfileList[0:params.maxCosponsors]

        # If we have audio clips after checking for activity start and end times
        if len(validfileList) > 0:
            # Clear the noDataAvailable flag
            data.noDataAvailable = 0

            # Update data with filename (2nd half of tuple in audiofileList element) only
            data.audioFile = validfileList[nvdata.count % len(validfileList)] + '.wav'
            data.imageFile = validfileList[nvdata.count % len(validfileList)] + '.tif'
        else:
            # No audio files were found
            data.audioFile = None
            data.imageFile = None

        # Update the counter for the next time
        nvdata.count += 1
        dsm.set(key, nvdata, 0)
        # We don't want to be doing a ds.commit() while the products are loading.
        # Because we are the only process to use this datastore entry, this should be safe.
        ### ds.commit()

