#!/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, scratchDb):

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

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

    '''
    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:
            if self.scratchDb.dbHost == "localhost":
                self.logger.info("dvopsps objects -parallel is incompatible with localhost for scratchdb")
                raise
                
            cmd += " -parallel"

        self.logger.infoPair("Running dvopsps", cmd)
        p = Popen(cmd, shell=True, stdout=PIPE)
        p.wait()
        if p.returncode != 0:
            self.logger.errorPair("dvopsps failed on ", region)
            raise

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

        return True
