# -*- coding: utf-8 -*-
import json
import indicoio

from flask import request
from flask_restful import Resource, abort

input_error_409 = 'Input must be a list of JSON objects. JSON objects must contain contain key text.'
service_error_503 = 'The sentiment analysis service is currently unavailable.'

class Analysis(Resource):
	def get(self):
		return "POST a list of JSON objects as content-type: application/json. JSON objects must contain key 'text'.", 405
		
	def post(self):
		if not request.json or not isinstance(request.json, (list,)):
			return abort(409, message=input_error_409)
		texts = request.json
		text_array = []
		value = 0
		for text in texts:
			if 'text' not in text:
				return abort(409, message=input_error_409)
			text_array.append(text['text'])
		try:
			for sentiment_value in indicoio.sentiment(text_array):
				value += sentiment_value
		except:
			return abort(503, message=service_error_503)
		sentiment = value/len(text_array)
		data = {'sentiment': sentiment}
		return data
