from zope.interface import implementer
from slapos.grid.promise import interface
from slapos.grid.promise.generic import GenericPromise
import time
import xml.etree.ElementTree as ET
import sys
from os.path import exists



@implementer(interface.IPromise)
class RunPromise(GenericPromise):
  def __init__(self, config):
    super(RunPromise, self).__init__(config)
    self.setPeriodicity(minute=10)

  def sense(self):
    log_file = self.getConfig('site-state-file')
    file_exists = exists(log_file)
    if not file_exists:
      self.logger.info('wait for crawler')
      return
    tree = ET.parse(log_file)
    root = tree.getroot()
    error = False
    for url in root.findall('url'):
      loc = url.find('loc').text
      referrer_tag = url.find('referrer')
      cache_control_tag = url.find('stateData/headers/cache-control')
      if not getattr(cache_control_tag, 'text', None):
        error = True
        referrer = getattr(referrer_tag, 'text', None)
        if referrer:
          message = "***%s has no cache defined in %s ---\n" % (loc, referrer)
        else:
          message = "***%s has no cache defined ---\n" % loc
        self.logger.error(message)
    if not error:
      self.logger.info("Site is ok")

  def test(self):
    return self._test(result_count=1, failure_amount=1)

  def anomaly(self):
    return self._test(result_count=3, failure_amount=3)
