import sys, ctypes, os, shutil, time, requests, json, logging, traceback
from plugin import Plugin

import ConfigParser
CONFIG_PATH = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'config.ini')

S_PATH = 'path'
O_PROCESS = 'process'
O_DONE = 'done'
O_ERROR = 'error'
O_URL = 'url'
O_TOOL = 'tool'

class ServiceWorker():

	def __init__(self):
		requests_log = logging.getLogger("requests.packages.urllib3")
		requests_log.setLevel(logging.CRITICAL)
		requests_log.propagate = True

		logging.debug("Worker initialization...")
		self.worker = Plugin()
		self.config = None
		self.read_config()
		logging.debug("Worker initialization done!")

	def work(self):
 		requestFile = None
		text=""
		while True:
			try:
				#print "czekam"
				r = requests.post(self.url, data=json.dumps(self.data), headers=self.headers)
				text=r.text		
				task = json.loads(text)
				#print "mam"
				if not task['task']:
					time.sleep(0.1)
				else:
					requestFile = task['task'].encode('ascii', 'ignore')
					self.run_worker_process(task)
			except requests.exceptions.RequestException as e:
   				logging.warning(e)
				time.sleep(60)
			except Exception as e:
				logging.error(e)
				logging.info(text)
				print traceback.format_exc()
				self._write_error_log(str(e), requestFile)
				if os.path.exists(self.process+requestFile):
					os.remove(self.process+requestFile) 
				
		return 0

	def read_config(self):
		with open(CONFIG_PATH) as config_file:
			self.config = ConfigParser.RawConfigParser()
			self.config.readfp(config_file)
			self.process = self.config.get(S_PATH, O_PROCESS)
			self.done = self.config.get(S_PATH, O_DONE)
			self.url = self.config.get(S_PATH, O_URL)
			self.error = self.config.get(S_PATH, O_ERROR)
			self.headers = {'Content-type': 'application/json'}
			self.data = {"tool": self.config.get(S_PATH, O_TOOL) }

	def run_worker_process(self, task):
		requestFile = task['task'].encode('ascii', 'ignore')
		options = task['options'].encode('ascii', 'ignore')
		logging.info("New task: " + requestFile)

		processPath = os.path.join(self.process, requestFile)
		donePath = os.path.join(self.done, requestFile)
		self.worker.process(processPath, donePath, options)

		os.remove(processPath)
		logging.info("Task " + requestFile + " complete!")

	def _write_error_log(self, exc_message, token):
		errorFileName = 'general' if (token is None) else token
		errorFilePath = os.path.join(self.error, errorFileName)
		errorFile = open(errorFilePath, 'w+')
		errorFile.write(exc_message)
		errorFile.close()
