#!/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 DvoForcedObjects(Dvo):

    '''
    Constructor
    '''
    def __init__(self, logger, config, skychunk, ippToPspsDb, scratchDb, gpc1Db):

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

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

    '''
    ingest forced 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/cpy/object table?
        # create detections table?

        # TODO path to DVO prog hardcoded temporarily
        # TODO this needs to be modified for forced objects
        cmd = "dvopsps forced_warp_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.config.test:
            cmd += " -test-mode"

        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
