/*
 * openwms.org, the Open Warehouse Management System.
 * Copyright (C) 2014 Heiko Scherrer
 *
 * This file is part of openwms.org.
 *
 * openwms.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as 
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * openwms.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this software. If not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.openwms.tms.api;

import static java.util.Arrays.asList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;

import org.ameba.exception.BehaviorAwareException;
import org.ameba.exception.BusinessRuntimeException;
import org.ameba.exception.NotFoundException;
import org.ameba.http.Response;
import org.ameba.mapping.BeanMapper;
import org.openwms.tms.PriorityLevel;
import org.openwms.tms.TMSConstants;
import org.openwms.tms.TransportOrder;
import org.openwms.tms.TransportationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriTemplate;

/**
 * A TransportationController.
 *
 * @author <a href="mailto:scherrer@openwms.org">Heiko Scherrer</a>
 * @version 1.0
 * @since 1.0
 */
@RestController
class TransportationController {

    @Autowired
    private BeanMapper m;
    @Autowired
    private TransportationService<TransportOrder> service;

    @RequestMapping(method = RequestMethod.GET, value = TMSConstants.ROOT_ENTITIES + "/{pKey}")
    public TransportOrder findByPKey(@PathVariable String pKey) {
        return service.findByPKey(pKey);
    }

    @RequestMapping(method = RequestMethod.POST, value = TMSConstants.ROOT_ENTITIES)
    public void createTO(@RequestBody CreateTransportOrderVO vo, HttpServletRequest req, HttpServletResponse resp) {
        validatePriority(vo);
        TransportOrder to = service.create(vo.getBarcode(), vo.getTarget(), PriorityLevel.valueOf(vo.getPriority()));
        resp.addHeader(HttpHeaders.LOCATION, getCreatedResourceURI(req, to.getPersistentKey()));
        resp.setStatus(201);
    }

    @RequestMapping(method = RequestMethod.PATCH, value = TMSConstants.ROOT_ENTITIES)
    public void updateTO(@RequestBody CreateTransportOrderVO vo, HttpServletResponse resp) {
        validatePriority(vo);
        service.update(m.map(vo, TransportOrder.class));
        resp.setStatus(204);
    }

    @ExceptionHandler(BusinessRuntimeException.class)
    public ResponseEntity<Response<Serializable>> handleNotFound(HttpServletResponse res, BusinessRuntimeException ex) throws Exception {
        if (ex instanceof BehaviorAwareException) {
            BehaviorAwareException bae = (BehaviorAwareException) ex;
            return new ResponseEntity<>(new Response<>(ex.getMessage(), bae.getMsgKey(), bae.getStatus().toString(), bae.getData()), bae.getStatus());
        }
        return new ResponseEntity<>(new Response<>(ex.getMessage(), ex.getMsgKey(), HttpStatus.INTERNAL_SERVER_ERROR.toString(), new String[]{ex.getMsgKey()}), HttpStatus.INTERNAL_SERVER_ERROR);
    }

    private void validatePriority(@RequestBody CreateTransportOrderVO vo) {
        asList(PriorityLevel.values()).stream()
                .filter(p -> p.name().equals(vo.getPriority()))
                .findFirst()
                .orElseThrow(() -> new NotFoundException(String.format("A priority level of %s is not defined", vo.getPriority())));
    }

    private String getCreatedResourceURI(HttpServletRequest req, String objId) {
        StringBuffer url = req.getRequestURL();
        UriTemplate template = new UriTemplate(url.append("/{objId}/").toString());
        return template.expand(objId).toASCIIString();
    }
}

@@ -1775,28 +1775,87 @@
 otation.
-PathVariable
+GetMapping;%0Aimport org.springframework.web.bind.annotation.PatchMapping
 ;%0Aimport
@@ -1895,27 +1895,28 @@
 otation.
-RequestBody
+PathVariable
 ;%0Aimport
@@ -1956,21 +1956,18 @@
 otation.
-Reque
+Po
 stMappin
@@ -2023,22 +2023,20 @@
 .Request
-Meth
+B
 od
+y
 ;%0Aimport
@@ -2252,24 +2252,8 @@
 /a%3E%0A
- * @version 1.0%0A
  * @
@@ -2258,17 +2258,17 @@
  @since 
-1
+2
 .0%0A */%0A@
@@ -2281,16 +2281,44 @@
 ntroller
+(TMSConstants.ROOT_ENTITIES)
 %0Aclass T
@@ -2461,30 +2461,26 @@
 vice;%0A%0A    @
-Reques
+Ge
 tMapping(met
@@ -2480,44 +2480,8 @@
 ing(
-method = RequestMethod.GET, value = 
 TMSC
@@ -2627,37 +2627,34 @@
 y);%0A    %7D%0A%0A    @
-Reque
+Po
 stMapping(method
@@ -2650,73 +2650,8 @@
 ping
-(method = RequestMethod.POST, value = TMSConstants.ROOT_ENTITIES)
 %0A   
@@ -3054,88 +3054,20 @@
    @
-RequestMapping(method = RequestMethod.PATCH, value = TMSConstants.ROOT_ENTITIES)
+PatchMapping
 %0A   

enable maven logging to avoid travis ci timeouts