#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Note: this stub doesn't try to fully simulate the map editor's social layer
#       if you needanytyhing that's not here yet you have to implement it but
#       in a way that existing users of this stub remain functional

from flask import Flask, request, make_response
import json
import sys


app = Flask(__name__)
sys.stdout = sys.stderr


def _nextFeedbackId():
    _nextFeedbackId._id += 1
    return str(_nextFeedbackId._id)
_nextFeedbackId._id = 0


def _makeResponse(body):
    if _makeResponse._serverError:
        _makeResponse._serverError = False
        return make_response(body, 500)
    else:
        _makeResponse._serverError = True
    return make_response(body, 200)
_makeResponse._serverError = True


def makeResponseBody(body, ftType=None, descr=None):
    print('RECEIVED:\n{body}'.format(body=body))

    data = json.loads(body)
    data[u'feedbackTask'] = {
        u'id': _nextFeedbackId(),
        u'created_at': u'2018-03-23T12:00:00+00:00'
    }
    if ftType is not None:
        data[u'type'] = ftType
    if descr is not None:
        data[u'description'] = descr

    return json.dumps(data)


@app.route('/feedback/tasks/absent-barrier', methods=['POST'])
def absent_barrier():
    body = makeResponseBody(request.data,
                            u'absent-barrier',
                            u'На карте отсутствует шлагбаум')
    return _makeResponse(body)


@app.route('/feedback/tasks', methods=['POST'])
def tasks():
    body = makeResponseBody(request.data)
    return _makeResponse(body)


def main(argv=sys.argv):
    # Make flask to use HTTP/1.1 protocol (to support Keep Alive connections)
    from BaseHTTPServer import BaseHTTPRequestHandler
    BaseHTTPRequestHandler.protocol_version = "HTTP/1.1"

    app.run(sys.argv[1], sys.argv[2])


if __name__ == '__main__':
    main()
