package com.jasamedika.medifirst2000.controller;

import com.jasamedika.medifirst2000.constants.MessageResource;
import com.jasamedika.medifirst2000.controller.base.LocaleController;
import com.jasamedika.medifirst2000.exception.ServiceVOException;
import com.jasamedika.medifirst2000.service.DistribusiAsetService;
import com.jasamedika.medifirst2000.service.ProdukService;
import com.jasamedika.medifirst2000.vo.DistribusiAsetVO;
import com.jasamedika.medifirst2000.vo.KonfirmasiAsetVO;
import com.jasamedika.medifirst2000.vo.PenerimaanBarangVO;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.orm.jpa.JpaSystemException;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Map;

import static com.jasamedika.medifirst2000.constants.Constants.MessageInfo.ERROR_MESSAGE;
import static com.jasamedika.medifirst2000.core.web.WebConstants.HttpHeaderInfo.LABEL_SUCCESS;
import static com.jasamedika.medifirst2000.util.rest.RestUtil.getJsonHttpStatus;
import static com.jasamedika.medifirst2000.util.rest.RestUtil.getJsonResponse;
import static java.net.URLDecoder.decode;
import static org.slf4j.LoggerFactory.getLogger;
import static org.springframework.http.HttpStatus.*;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

@RestController
@RequestMapping("/distribusi-aset")
public class DistribusiAsetController extends LocaleController<PenerimaanBarangVO> {

	private static final Logger LOGGER = getLogger(DistribusiAsetController.class);

	@Autowired
	private DistribusiAsetService distribusiAsetService;

	@Autowired
	private ProdukService produkService;

	@RequestMapping(value = "/find-produk-aset", method = GET)
	public Map<String, Object> findProdukAset(HttpServletRequest request) {
		String data = request.getQueryString();
		data = decode(data);
		String[] arrQueries = data.split("&");
		StringBuilder criteria = new StringBuilder();
		StringBuilder values = new StringBuilder();
		for (String query : arrQueries) {
			if (query.contains("filter[filters][0][field]")) {
				criteria.append(",").append(query.replace("filter[filters][0][field]=", ""));
			} else if (query.contains("filter[filters][0][value]")) {
				values.append(query.replace("filter[filters][0][value]=", ""));
			}
		}
		return produkService.findProdukAset(values.toString());
	}

	@RequestMapping(value = "/find-aset-by-produk", method = GET)
	public Map<String, Object> findAsetByProduk(@RequestParam(value = "id", required = false) Integer id,
			HttpServletRequest request) {
		String data = request.getQueryString();
		data = decode(data);
		String[] arrQueries = data.split("&");
		StringBuilder criteria = new StringBuilder();
		StringBuilder values = new StringBuilder();
		for (String query : arrQueries) {
			if (query.contains("filter[filters][0][field]")) {
				criteria.append(",").append(query.replace("filter[filters][0][field]=", ""));
			} else if (query.contains("filter[filters][0][value]")) {
				values.append(query.replace("filter[filters][0][value]=", ""));
			}
		}
		return produkService.findAsetByProduk(id, values.toString());
	}

	@RequestMapping(value = "/save-distribusi-aset/", method = POST, produces = APPLICATION_JSON_VALUE, consumes = APPLICATION_JSON_VALUE)
	public ResponseEntity<Map<String, Object>> saveDistribusiAset(@Valid @RequestBody DistribusiAsetVO vo,
			HttpServletRequest request, HttpServletResponse response) {
		try {
			Map<String, Object> result = distribusiAsetService.saveRequestDistribusi(vo);
			if (null != result)
				mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
			return getJsonResponse(result, CREATED, mapHeaderMessage);
		} catch (ServiceVOException e) {
			LOGGER.error("Got ServiceVOException {} when saveRequestDistribusi", e.getMessage());
			addHeaderMessage(ERROR_MESSAGE, e.getMessage());
			return getJsonHttpStatus(INTERNAL_SERVER_ERROR, mapHeaderMessage);
		} catch (JpaSystemException jse) {
			LOGGER.error("Got JpaSystemException {} when saveRequestDistribusi", jse.getMessage());
			addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
			return getJsonHttpStatus(CONFLICT, mapHeaderMessage);
		}
	}

	@RequestMapping(value = "/get-kirim-detail-permintaan-barang/", method = GET, produces = APPLICATION_JSON_VALUE)
	public ResponseEntity<Map<String, Object>> getKirimDetailPermintaanBarang(
			@RequestParam(value = "noRec") String noRec) {
		try {
			Map<String, Object> strukOrder = distribusiAsetService.findByStrukKirimNoRec(noRec);
			return getJsonResponse(strukOrder, OK, mapHeaderMessage);
		} catch (IllegalArgumentException e) {
			throw new ServiceVOException(e.getMessage());
		}
	}

	@RequestMapping(value = "/save-konfirmasi-aset/", method = POST, produces = APPLICATION_JSON_VALUE, consumes = APPLICATION_JSON_VALUE)
	public ResponseEntity<Map<String, Object>> saveKonfirmasiAset(@Valid @RequestBody KonfirmasiAsetVO vo,
			HttpServletRequest request, HttpServletResponse response) {
		try {
			Map<String, Object> result = distribusiAsetService.saveKonfirmasiAset(vo);
			if (null != result)
				mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
			return getJsonResponse(result, CREATED, mapHeaderMessage);
		} catch (ServiceVOException e) {
			LOGGER.error("Got ServiceVOException {} when saveKonfirmasiAset", e.getMessage());
			addHeaderMessage(ERROR_MESSAGE, e.getMessage());
			return getJsonHttpStatus(INTERNAL_SERVER_ERROR, mapHeaderMessage);
		} catch (JpaSystemException jse) {
			LOGGER.error("Got JpaSystemException {} when saveKonfirmasiAset", jse.getMessage());
			addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
			return getJsonHttpStatus(CONFLICT, mapHeaderMessage);
		}
	}

}
