#!/usr/bin/env python
# coding: utf-8
import time
import os
import json
import logging

import schedule
import requests
from envelopes import Envelope, SMTP

from .daemon3 import Daemon


class Worker(Daemon):

    def __init__(self, *args, **kwargs):
        super(Worker, self).__init__(*args, **kwargs)

        self.config = self.load_configuration()

        #check if external mail server
        self.external_mail_server = False
        if self.config.get("emailServer",None):
            if self.config.get("emailLogin",None) and \
               self.config.get("emailPassword",None):
               self.external_mail_server = True

        #logging
        logPath = self.config.get("logPath", None)
        if logPath:
            self.init_logger(logPath)
        else:
            self.init_logger("%s%s" % (os.path.expanduser("~"), "/augure.log"))

        self.urlStates = {}

    def run(self):
        self.logger.info("Augure is watching")
        schedule.every().minute.do(self.check)
        self.check()

        while True:
            self.logger.debug("check pending job")
            schedule.run_pending()
            time.sleep(1)

    def check(self):
        for url in self.config['urls']:
            r = None
            try:
                r = requests.get(url)
            except:
                pass

            if not r or r.status_code != 200:
                message = "%s is not accessible" % (url)
                if r and r.status_code:
                    message = "%s, status %s" % (message, r.status_code)
                self.logger.warning(message)

                if self.config.get('emailRecipient', None):

                    # if state was ok before (anti spam)
                    if self.urlStates.get(url, True):
                        self.urlStates[url] = False
                        self.send_mail(message)

            else:
                self.urlStates[url] = True

    def send_mail(self, text):
        self.logger.debug("Building mail")

        envelope = Envelope(
            from_addr=('augure@augure.nowhere'),
            to_addr=self.config.get('emailRecipient', None),
            subject='The Augure has spoken',
            text_body=text
        )

        try:
            self.logger.debug("Sending mail")
       
            if self.external_mail_server:
                envelope.send(
                    self.config.get("emailServer"), 
                    login=self.config["emailLogin"],
                    password=self.config["emailPassword"], tls=True
                )
            else:
                #if no mail in config we use local mail server
                envelope.send('localhost', port=25)

            self.logger.debug("Mail sent")
        except Exception as e:
            self.logger.error(e)

    def load_configuration(self, filename=None):
        configFile = None
        if filename and os.path.isfile(filename):
            configFile = filename
        if os.path.isfile("/etc/augure/augure.conf"):
            configFile = "/etc/augure/augure.conf"

        homeConfiguration = "%s%s" % (
            os.path.expanduser("~"), "/.augure/augure.conf")
        if os.path.isfile(homeConfiguration):
            configFile = homeConfiguration

        if not configFile:
            raise Exception("No Configuration file found")

        try:
            with open(configFile) as data_file:
                data = json.load(data_file)
                self.config = data
                return data
        except Exception as e:
            logging.error(e)
            raise Exception("Error in %s: %s" % (configFile, e))

    def init_logger(self, path=None):
        if(path):
            logging.basicConfig(
                format='%(asctime)s %(levelname)s:%(message)s',
                filename=path,
                level=logging.DEBUG
            )
        self.logger = logging.getLogger(__name__)

@@ -649,35 +649,25 @@
     
-#logging%0A        logPath = 
+self.init_logger(
 self
@@ -698,159 +698,8 @@
 one)
-%0A        if logPath:%0A            self.init_logger(logPath)%0A        else:%0A            self.init_logger(%22%25s%25s%22 %25 (os.path.expanduser(%22~%22), %22/augure.log%22)
 )%0A%0A 
@@ -2905,25 +2905,24 @@
 e.conf%22%0A
-%0A
         
 homeConf
@@ -2917,51 +2917,130 @@
     
-homeConfiguration = %22%25s%25s%22 %25 (%0A            
+if os.path.isfile(%22/etc/augure/augure.conf%22):%0A            configFile = %22/etc/augure.conf%22)%0A%0A        home_conf = %22%25s%25s%22 %25 (
 os.p
@@ -3059,17 +3059,16 @@
 er(%22~%22),
- 
 %22/.augur
@@ -3589,37 +3589,28 @@
 ath=
-None):%0A        if(path):%0A    
+%22/tmp/augure.log%22):%0A
     
@@ -3634,20 +3634,16 @@
 Config(%0A
-    
         
@@ -3706,20 +3706,16 @@
         
-   
- 
 filename
@@ -3733,20 +3733,16 @@
         
-    
 level=lo
@@ -3751,13 +3751,12 @@
 ing.
-DEBUG
+INFO
 %0A   
@@ -3756,33 +3756,32 @@
 NFO%0A            
-)
 %0A        self.lo

clean logger