#!/usr/bin/env jython

from subprocess import call, PIPE, Popen
import tempfile
import logging
import sys
import re
from xml.etree.ElementTree import ElementTree, Element, tostring

from ipptopspsdb import IppToPspsDb

'''
Class encapsulating the IPP datastore
'''
class Datastore(object):

    '''
        Constructor

    '''
    def __init__(self, logger, doc, ippToPspsDb):
    
        # setup logger
        self.logger = logger
        self.doc = doc
        self.ippToPspsDb = ippToPspsDb
        self.logger.debug("Datastore constructor")

        # open config
        self.product = doc.find("datastore/product").text
        self.type = doc.find("datastore/type").text

        self.logger.debug("Using product: '" + self.product + "' and type: '" + self.type + "'")

    '''
    Publishes an item to the datastore
    '''
    def publish(self, name, path, file, fileType):

        # TODO should handle this better
        batchID = int(name[1:])

        self.logger.infoPair("Attempting to publish",  path + "/" + file)
        tempFile = tempfile.NamedTemporaryFile(mode='w+b')
        tempFile.write(file + "|||" + fileType)
        tempFile.seek(0)

        # build dsreg command
        command  = "dsreg --add " + name + "\
                    --link --datapath " + path + "\
                    --type " + self.type + "\
                    --product " + self.product + "\
                    --list " + tempFile.name

        p = Popen(command, shell=True, stdout=PIPE)
        p.wait()

        if p.returncode != 0:
            self.logger.errorPair("Datastore publish",  "failed")
            ret = False
            self.ippToPspsDb.updateLoadedToDatastore(batchID, -1)
        else:
            self.logger.infoPair("Datastore publish", "successful")
            ret = True
            self.ippToPspsDb.updateLoadedToDatastore(batchID, 1)
            
        tempFile.close()

        return ret

    '''
    Removes an item from the datastore

    NB this will return a success if the batch is not found on the datastore
    '''
    def remove(self, name):

        # TODO should handle this better
        batchID = int(name[1:])

        command = "dsreg \
                   --del " + name + " \
                   --rm \
                   --product " + self.product

        p = Popen(command, shell=True, stdout=PIPE, stderr=PIPE)
        p.wait()
        output, errors = p.communicate()

        if p.returncode != 0:
            if re.search("not found in", errors):
                self.logger.infoPair("Datastore batch not found", name)
                ret = True
                self.ippToPspsDb.updateDeletedDatastore(batchID, 1)
            else:
                self.logger.infoPair("Datastore removal FAILED", name)
                ret = False
        else:
            self.logger.infoPair("Datastore removal successful", name)
            ret = True
            self.ippToPspsDb.updateDeletedDatastore(batchID, 1)
            
        return ret

    '''
    Removes a range of items from the datastore
    '''
    def removeRange(self, first, last):

        firstInt = int(first[1:])
        lastInt = int(last[1:])

        for i in range(firstInt, lastInt):
            
            self.remove(Batch.getNameFromID(i))

from batch import Batch
