import xmltodict
from helper import *
from Device import Inverter
from utilities import *
import logging

from volttron.platform.agent import utils

DEBUG = True
xml_path = get_xml_path()
utils.setup_logging()
_log = logging.getLogger(__name__)

class DERProgramList(object):
    '''
	Extracts and creates the DER Programs 
    '''
    def __init__(self, href, inverter):
        if DEBUG:
	    self.file = os.path.join(xml_path,"DERProgramList.xml")
            self.response = xmltodict.parse(open(self.file).read())
        else:
            self.response = GET(href)
        self.href = href
        Pgms = self.response['DERProgramList']['DERProgram']
        self.pollRate = self.response['DERProgramList']['@pollRate']
        self.Pgms = []
        self.Pgm_mRIDs = []
        for pgm in Pgms:
            self.Pgm_mRIDs = pgm['mRID']
            self.Pgms.append(DERProgram(pgm, inverter))

    def poll(self):
        changed, res = check_content(self, 'DERProgramList', 'DERProgram')
        if changed:
            self.response = res
            newPgm_mRIDS = [x['mRID'] for x in newPgmList]
            temp = set(newPgm_mRIDS).symmetric_difference(set(Pgm_mRIDs))
            if len(temp>0):
                x.add([l for l in z.difference(x)])
                self.Pgm_mRIDs.remove([l for l in temp.difference(set(newPgm_mRIDS))])
                self.Pgms.remove([self.get_pgm_by_mRID(l, self.Pgms) for l in temp.difference(set(newPgm_mRIDS))])

                self.Pgm_mRIDs.append([l for l in temp.difference(set(Pgm_mRIDs))])
                self.Pgms.append([DERProgram(self.get_pgm_by_mRID(l, newPgmList)) for l in temp.difference(set(Pgm_mRIDs))])
                
            for pgm in self.Pgms:
                pgm.set_poll_values(newPgmList)

    def get_pgm_by_mRID(self, id, pgms):
        return [p for p in pgms if p.mRID == id]


class DERProgram(DERProgramList):
    def __init__(self, Program, inverter):
        self.Program = Program
        self.mRID = Program['mRID']
        self.set_poll_values(Program)
        self.inverter = inverter
	self.link = Program['@href']
	self.DefaultDERControl = DefaultDERControl(Program['DefaultDERControlLink']['@href'], self.inverter)