#!/usr/bin/env jython

import stilts
import datetime
import re
import sys
import os
import logging
import glob
from subprocess import call, PIPE, Popen

from dvo import Dvo

'''
A class for ingesting DVO detections into MySQL
'''
class DvoObjects(Dvo):

    '''
    Constructor
    '''
    def __init__(self, logger, config, skychunk, ippToPspsDb, scratchDbName=None):

        super(DvoObjects, self).__init__(logger, config, skychunk, ippToPspsDb, scratchDbName)

        # declare DVO file types of interest
        self.ingestFileTypes = ['cpt', 'cps']
        self.loadPhotcodes()

    '''
    Ingests object files for this region
    '''
    def ingestRegion(self, region):

       self.logger.infoPair("Ingesting objects for", region)

       for fileType in self.ingestFileTypes:

           path = self.skychunk.dvoLocation + "/" + region + "." + fileType
           tableName = self.scratchDb.getDbFriendlyTableName(region + "." + fileType)

           self.importFits(path, "*", tableName)

           self.scratchDb.setImportedThisDvoTable(path, region)

       return True


    '''
    ingest object data into MySQL database using the native DVO program dvopsps
    Populates dvoDetections and dvoDone with FITS tables from DVO for the defined sky area, this
    includes purging detections outside sky area
    '''
    def nativeIngestRegion(self, region):

        # drop cpt/cps/object table?
        # create detections table?

        # TODO path to DVO prog hardcoded temporarily
        cmd = "dvopsps objects"
        cmd += " -dbhost " + self.scratchDb.dbHost
        cmd += " -dbname " + self.scratchDb.dbName
        cmd += " -dbuser " + self.scratchDb.dbUser
        cmd += " -dbpass " + self.scratchDb.dbPass
        cmd += " -D CATDIR " + self.skychunk.dvoLocation
        cmd += " -cpt " + region

        if self.skychunk.parallel:
            cmd += " -parallel"

        self.logger.infoPair("Running dvopsps", cmd)
        p = Popen(cmd, shell=True, stdout=PIPE)
        p.wait()

        # update lists after attempted sync
        # self.printSummary()

        return True
