#!/usr/bin/env python3

import sys
import requests
import os
import json

try:
    cmd = sys.argv[1]
except:
    cmd = 'help'

eq = sys.argv[2:]


ENDPOINT = os.getenv('apiAPS')

# print(ENDPOINT)
# print(cmd, eq)


def jsonify(data):
    json = {}

    json['taskName'] = data[0]
    # for task in data:
    #     taskName = task.split(":")[0]
    #     taskValue = task.split(":")[1]
    #     json[taskName] = taskValue

    return json


def addTask(data):
    res = requests.post('{}/Tarefa'.format(ENDPOINT), json=data)
    return res.content, res.status_code


def listTask():
    res = requests.get('{}/Tarefa'.format(ENDPOINT))
    return res.content, res.status_code


def searchTask(data):
    idTask = data[0]
    res = requests.get('{}/Tarefa/{}'.format(ENDPOINT, idTask))
    return res.content, res.status_code


def deleteTask(data):
    idTask = data[0]
    res = requests.delete('{}/Tarefa/{}'.format(ENDPOINT, idTask))
    return res.content, res.status_code


def updateTask(data):
    idTask = data[0]
    newValue = {'updatedTask': data[1]}
    res = requests.put('{}/Tarefa/{}'.format(ENDPOINT, idTask), json=newValue)
    return res.content, res.status_code


def help():
    print('''Uso : tarefa [OPTIONS]

Configurar uma variavel de ambiente apiAPS

Comandos:
    adicionar NomeTarefa
    listar
    buscar IdTarefa
    apagar IdTarefa
    atualizar IdTarefa NovoValor
             
''')


if cmd == 'adicionar':
    data = jsonify(eq)
    print(data)
    req = addTask(data)
    print(req[0])
elif cmd == 'listar':
    req = listTask()
    print(req[0])
elif cmd == 'buscar':
    req = searchTask(eq)
    print(req[0])
elif cmd == 'apagar':
    req = deleteTask(eq)
    print(req[0])
elif cmd == 'atualizar':
    req = updateTask(eq)
    print(req[0])
else:
    help()
