# Path: _15thnight/core.py
# def resolve_need(need):
#     """
#     Resolve a need and trigger an alert closed if necessary.
#     """
#     alert = need.alert
#     advocate = alert.user
#     message = ''
#     if need.resolve_message != '':
#         message = '\nMsg: ' + need.resolve_message
#     gender = alert.get_gender()
#     args = (advocate.name, advocate.organization,
#             need.service.name, alert.age, gender)
#     accepted = ('15th Night help accepted!\n'
#                 '%s with %s selected you to provide %s for a '
#                 '%d y/o%s%s') % (args + (message,))
#     denied = ('15th Night help not needed\n'
#               '%s with %s does not need your help to provide %s for a '
#               '%d y/o%s') % args
# 
#     selected = set()
#     users = set(map(
#         lambda provision: provision.response.user, need.provisions))
#     for provision in need.provisions:
#         if provision.selected:
#             selected.add(provision.response.user_id)
# 
#     for provider in users:
#         body = accepted if provider.id in selected else denied
#         queue_send_message.apply_async(
#             kwargs=dict(
#                 email=advocate.email,
#                 number=advocate.phone_number,
#                 subject='15th Night Need Resolution',
#                 body=body
#             )
#         )
#     # Check if alert is closed, if so, send out resolution notices
#     _send_alert_resolution_notice(need)
# 
# Path: _15thnight/forms.py
# class ResolveNeedForm(Form):
#     notes = TextField('Notes')
#     message = TextField('Message')
#     provisions = SelectMultipleField('Provisions', choices=[], coerce=int)
# 
#     def __init__(self, *args, **kwargs):
#         super(ResolveNeedForm, self).__init__(*args, **kwargs)
#         need = kwargs.get('need')
#         self.provisions.choices = [
#             (provision.id, provision.id) for provision in need.provisions
#         ]
# 
# Path: _15thnight/models.py
# class Need(Model):
#     __tablename__ = 'need'
# 
#     id = Column(Integer, primary_key=True)
#     alert_id = Column(ForeignKey('alerts.id'), nullable=False)
#     alert = relationship('Alert', backref='needs')
#     service_id = Column(ForeignKey('service.id'), nullable=False)
#     service = relationship('Service')
#     resolved = Column(Boolean, default=False, nullable=False)
#     resolved_at = Column(DateTime)
#     resolve_notes = Column(Text)
#     resolve_message = Column(Text)
# 
#     @classmethod
#     def get_by_id_and_alert(cls, need_id, alert):
#         return cls.query.filter(
#             (cls.alert == alert) & (cls.id == need_id)).first()
# 
#     def to_json(self):
#         return dict(
#             id=self.id,
#             alert_id=self.alert_id,
#             service=self.service,
#             resolved=self.resolved,
#             resolved_at=to_local_datetime(self.resolved_at)
#         )
# 
#     def to_advocate_json(self):
#         return extend(self.to_json(), dict(
#             provisions=[
#                 provision.to_advocate_json() for provision in self.provisions
#             ]
#         ))
# 
#     def to_provider_json(self, provider):
#         return extend(self.to_json(), dict(
#             provisions=NeedProvided.get_by_need_and_provider(self, provider)
#         ))
# 
# Path: _15thnight/util.py
# def api_error(message='Bad Request', code=400):
#     return jsonify(error=message, _status_code=code)
# 
# def jsonify(*args, **kwargs):
#     """Returns a json response"""
#     data = None
#     indent = not request.is_xhr
#     status = kwargs.pop('_status_code', 200)
#     if args:
#         data = args[0] if len(args) == 1 else args
#     if kwargs:
#         if data:
#             if type(data) != list:
#                 data = [data]
#             data.append(dict(**kwargs))
#         else:
#             data = dict(**kwargs)
#     return current_app.response_class(
#         dumps(data, indent=indent), status=status, mimetype='application/json'
#     )
# 
# def required_access(*roles):
#     def templated(f):
#         @wraps(f)
#         def decorated(*args, **kwargs):
#             if current_user.is_anonymous or current_user.role not in roles:
#                 return 'Access Denied.', 403
#             return f(*args, **kwargs)
#         return decorated
#     return templated


from datetime import datetime
from flask import Blueprint
from flask.ext.login import current_user
from _15thnight.core import resolve_need
from _15thnight.forms import ResolveNeedForm
from _15thnight.models import Need
from _15thnight.util import api_error, jsonify, required_access



need_api = Blueprint('need_api', __name__)


@need_api.route('/<int:need_id>')
@required_access('advocate', 'admin')
def get_need(need_id):
    need = Need.get(need_id)
    if not need:
        return api_error('Need not found')
    if not current_user.is_admin and current_user.id != need.alert.user_id:
        return api_error('Permission denied')
    return jsonify(need.to_advocate_json())


@need_api.route('/<int:need_id>/resolve', methods=['POST'])

# Path: _15thnight/core.py
# def resolve_need(need):
#     """
#     Resolve a need and trigger an alert closed if necessary.
#     """
#     alert = need.alert
#     advocate = alert.user
#     message = ''
#     if need.resolve_message != '':
#         message = '\nMsg: ' + need.resolve_message
#     gender = alert.get_gender()
#     args = (advocate.name, advocate.organization,
#             need.service.name, alert.age, gender)
#     accepted = ('15th Night help accepted!\n'
#                 '%s with %s selected you to provide %s for a '
#                 '%d y/o%s%s') % (args + (message,))
#     denied = ('15th Night help not needed\n'
#               '%s with %s does not need your help to provide %s for a '
#               '%d y/o%s') % args
# 
#     selected = set()
#     users = set(map(
#         lambda provision: provision.response.user, need.provisions))
#     for provision in need.provisions:
#         if provision.selected:
#             selected.add(provision.response.user_id)
# 
#     for provider in users:
#         body = accepted if provider.id in selected else denied
#         queue_send_message.apply_async(
#             kwargs=dict(
#                 email=advocate.email,
#                 number=advocate.phone_number,
#                 subject='15th Night Need Resolution',
#                 body=body
#             )
#         )
#     # Check if alert is closed, if so, send out resolution notices
#     _send_alert_resolution_notice(need)
# 
# Path: _15thnight/forms.py
# class ResolveNeedForm(Form):
#     notes = TextField('Notes')
#     message = TextField('Message')
#     provisions = SelectMultipleField('Provisions', choices=[], coerce=int)
# 
#     def __init__(self, *args, **kwargs):
#         super(ResolveNeedForm, self).__init__(*args, **kwargs)
#         need = kwargs.get('need')
#         self.provisions.choices = [
#             (provision.id, provision.id) for provision in need.provisions
#         ]
# 
# Path: _15thnight/models.py
# class Need(Model):
#     __tablename__ = 'need'
# 
#     id = Column(Integer, primary_key=True)
#     alert_id = Column(ForeignKey('alerts.id'), nullable=False)
#     alert = relationship('Alert', backref='needs')
#     service_id = Column(ForeignKey('service.id'), nullable=False)
#     service = relationship('Service')
#     resolved = Column(Boolean, default=False, nullable=False)
#     resolved_at = Column(DateTime)
#     resolve_notes = Column(Text)
#     resolve_message = Column(Text)
# 
#     @classmethod
#     def get_by_id_and_alert(cls, need_id, alert):
#         return cls.query.filter(
#             (cls.alert == alert) & (cls.id == need_id)).first()
# 
#     def to_json(self):
#         return dict(
#             id=self.id,
#             alert_id=self.alert_id,
#             service=self.service,
#             resolved=self.resolved,
#             resolved_at=to_local_datetime(self.resolved_at)
#         )
# 
#     def to_advocate_json(self):
#         return extend(self.to_json(), dict(
#             provisions=[
#                 provision.to_advocate_json() for provision in self.provisions
#             ]
#         ))
# 
#     def to_provider_json(self, provider):
#         return extend(self.to_json(), dict(
#             provisions=NeedProvided.get_by_need_and_provider(self, provider)
#         ))
# 
# Path: _15thnight/util.py
# def api_error(message='Bad Request', code=400):
#     return jsonify(error=message, _status_code=code)
# 
# def jsonify(*args, **kwargs):
#     """Returns a json response"""
#     data = None
#     indent = not request.is_xhr
#     status = kwargs.pop('_status_code', 200)
#     if args:
#         data = args[0] if len(args) == 1 else args
#     if kwargs:
#         if data:
#             if type(data) != list:
#                 data = [data]
#             data.append(dict(**kwargs))
#         else:
#             data = dict(**kwargs)
#     return current_app.response_class(
#         dumps(data, indent=indent), status=status, mimetype='application/json'
#     )
# 
# def required_access(*roles):
#     def templated(f):
#         @wraps(f)
#         def decorated(*args, **kwargs):
#             if current_user.is_anonymous or current_user.role not in roles:
#                 return 'Access Denied.', 403
#             return f(*args, **kwargs)
#         return decorated
#     return templated


# Path: _15thnight/api/need.py
from datetime import datetime
from flask import Blueprint
from flask.ext.login import current_user
from _15thnight.core import resolve_need
from _15thnight.forms import ResolveNeedForm
from _15thnight.models import Need
from _15thnight.util import api_error, jsonify, required_access




need_api = Blueprint('need_api', __name__)


@need_api.route('/<int:need_id>')
@required_access('advocate', 'admin')
def get_need(need_id):
    need = Need.get(need_id)
    if not need:
        return api_error('Need not found')
    if not current_user.is_admin and current_user.id != need.alert.user_id:
        return api_error('Permission denied')
    return jsonify(need.to_advocate_json())


@need_api.route('/<int:need_id>/resolve', methods=['POST'])

@required_access('advocate', 'admin')