#!/usr/bin/env python

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

app = Flask(__name__)

try_count = 0
OK_RATE = 3


def need_answer_500():
    global try_count
    try_count += 1

    return try_count % OK_RATE > 0


def response500():
    return make_response('Internal error', 500)


@app.route('/api/v1/pools', methods=['GET'])
def get_pools():
    if need_answer_500():
        return response500()

    with open('tests/json/pools.json', 'r') as pools:
        return make_response(pools.read(), 200)


@app.route('/api/v1/pools', methods=['POST'])
def create_pool():
    if need_answer_500():
        return response500()

    data = json.loads(request.data)

    data['id'] = 'pool-123'
    data['status'] = 'CLOSED'
    data['created'] = datetime.datetime.now().isoformat()
    return make_response(json.dumps(data), 201)


@app.route('/api/v1/tasks', methods=['GET'])
def get_tasks():
    if need_answer_500():
        return response500()

    with open('tests/json/tasks.json', 'r') as tasks:
        return make_response(tasks.read(), 200)


@app.route('/api/v1/tasks', methods=['POST'])
def post_task():
    if need_answer_500():
        return response500()

    data = json.loads(request.data)
    if isinstance(data, dict):
        data['id'] = 'task-123'
        data['created'] = datetime.datetime.now().isoformat()
        return make_response(json.dumps(data), 201)
    elif isinstance(data, list):
        resp = {"items": {}, "validation_errors": {}}
        count = 0
        for item in data:
            item['id'] = 'task-' + str(count)
            item['created'] = datetime.datetime.now().isoformat()
            resp['items'][str(count)] = item
            count += 1
        return make_response(json.dumps(resp), 201)


@app.route('/api/v1/tasks/<task_id>', methods=['PATCH'])
def patch_task(task_id):
    if need_answer_500():
        return response500()

    data = json.loads(request.data)
    data['id'] = task_id
    data['created'] = datetime.datetime.now().isoformat()
    data['input_values'] = {}
    data['pool_id'] = '1'

    return make_response(json.dumps(data), 200)


@app.route('/api/v1/task-suites', methods=['GET'])
def get_task_suites():
    if need_answer_500():
        return response500()

    with open('tests/json/task_suites.json', 'r') as task_suites:
        return make_response(task_suites.read(), 200)


@app.route('/api/v1/task-suites', methods=['POST'])
def post_task_suite():
    if need_answer_500():
        return response500()

    data = json.loads(request.data)

    if isinstance(data, dict):
        data['id'] = 'task-suite-123'
        data['created'] = datetime.datetime.now().isoformat()
        return make_response(json.dumps(data), 201)
    elif isinstance(data, list):
        resp = {"items": {}, "validation_errors": {}}
        count = 0
        for item in data:
            item['id'] = 'task-suite-' + str(count)
            item['created'] = datetime.datetime.now().isoformat()
            resp['items'][str(count)] = item
            count += 1
        return make_response(json.dumps(resp), 201)


@app.route('/api/v1/task-suites/<task_suite_id>', methods=['PATCH'])
def patch_task_suite(task_suite_id):
    if need_answer_500():
        return response500()

    data = json.loads(request.data)
    data['id'] = task_suite_id
    data['created'] = datetime.datetime.now().isoformat()
    data['tasks'] = []
    data['pool_id'] = '1'

    return make_response(json.dumps(data), 200)


@app.route('/api/v1/assignments', methods=['GET'])
def get_assignments():
    if need_answer_500():
        return response500()

    with open('tests/json/assignments.json', 'r') as assignments:
        return make_response(assignments.read(), 200)


@app.route('/api/v1/assignments/<assignment_id>', methods=['PATCH'])
def patch_assignment(assignment_id):
    if need_answer_500():
        return response500()

    data = json.loads(request.data)
    data['id'] = assignment_id
    data['created'] = datetime.datetime.now().isoformat()
    data['task_suite_id'] = '1'
    data['pool_id'] = '1'
    data['user_id'] = '1'
    data['tasks'] = []
    data['solutions'] = []

    return make_response(json.dumps(data), 200)


@app.route('/api/v1/requester', methods=['GET'])
def get_requester():
    if need_answer_500():
        return response500()

    with open('tests/json/requester.json', 'r') as requester:
        print(requester)
        return make_response(requester.read(), 200)


def main(argv=sys.argv):
    app.run(sys.argv[1], sys.argv[2])


if __name__ == "__main__":
    main()
