package com.bytesw.bytebot.controller;

import com.bytesw.bytebot.bean.FlightBean;
import com.bytesw.bytebot.bean.LegBean;
import com.bytesw.bytebot.bean.ReservationBean;
import com.bytesw.bytebot.service.LegService;
import com.bytesw.xdf.annotation.ProgramSecurity;
import com.google.gson.GsonBuilder;
import io.swagger.annotations.ApiParam;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.orm.ObjectOptimisticLockingFailureException;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController()
@RequestMapping("/service/settings/leg")
@ProgramSecurity("BUSINESS-PARAMETERS")
@Log4j2
public class LegController {

    @Autowired
    private LegService service;

    @Autowired
    protected GsonBuilder gson;

    @PostMapping(value = "/")
    public ResponseEntity<String> create(@RequestBody LegBean bean, HttpServletRequest req) {
        this.service.create(bean);
        return new ResponseEntity(gson.create().toJson(bean), HttpStatus.OK);
    }

    @GetMapping(value = "/flight/{id}")
    public ResponseEntity<String> findAllLegs(@ApiParam(value = "id", required = true) @PathVariable("id") Long id, HttpServletRequest req) {
        try {
            return new ResponseEntity<>(gson.create().toJson(this.service.getLeg(id)), HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(gson.create().toJson(ExceptionUtils.getFullStackTrace(e)), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @PutMapping(value = "/{id}")
    public ResponseEntity<String> update(@PathVariable("id") Long id, @RequestBody LegBean bean, HttpServletRequest req) {
        try {
            this.service.update(bean, id);
        } catch (ObjectOptimisticLockingFailureException var6) {
            return new ResponseEntity(gson.create().toJson("error"), HttpStatus.CONFLICT);
        }

        return new ResponseEntity(HttpStatus.OK);
    }
}
