from trytond.wsgi import app
from trytond.transaction import Transaction
from trytond.protocols.wrappers import (
    with_pool,
    with_transaction,
    user_application,
    allow_null_origin)
import json

sale_order_application = user_application('sale_order')


@app.route(
    '/<database_name>/sale_order/order', methods=['POST'])
@allow_null_origin
@with_pool
@with_transaction()
@sale_order_application
def post_order(request, pool):
    Order = pool.get('sale.order')
    with Transaction().set_context(
            {'company': 1, 'locations': [3]}):
        if request.method == 'POST':
            data = json.loads(
                request.get_data().decode()
            )
            order, = Order.create([dict(data)])

            response_data = {
                    'id': order.id,
                    'status': 'success',
                    'message': 'Order created successfully',
            }
            return json.dumps(response_data), 201


@app.route(
    '/<database_name>/sale_order/order/<order>', methods=['GET'])
@allow_null_origin
@with_pool
@with_transaction()
@sale_order_application
def get_order(request, pool, order: int):
    Order = pool.get('sale.order')
    with Transaction().set_context({
            'company': 1,
            'locations': [3]}):
        if request.method == 'GET':
            orders = Order.search_read([
                ('id', '=', order)
            ], order=[
                ('id', 'ASC')
            ], fields_names=[
                'id',
                'party',
                'lines'
            ])

            return orders


@app.route(
    '/<database_name>/sale_order/confirm_order/<order>', methods=['POST'])
@allow_null_origin
@with_pool
@with_transaction()
@sale_order_application
def confirm_order(request, pool, order: int):
    Order = pool.get('sale.order')
    if request.method == 'POST':
        order, = Order.search([
            ('id', '=', order)
        ])

        Order.confirm([order])

        response_data = {
            'id': order.id,
            'status': 'success',
            'state': order.state,
            'message': 'Order confirm successfully',
        }

        return json.dumps(response_data), 201