package controller.rest;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
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.ResponseBody;

import bean.AppVariables;
import bean.LogVariazioniBean;
import common.controller.BaseController;
import dao.LogVariazioniDAO;

@Controller
@RequestMapping("logModifiche")
public class LogModificheDisposizioniRestController extends BaseController {

	@Autowired
	LogVariazioniDAO logVariazioniDao;
	
	@RequestMapping(value="/list/{idDisposizione}")
	@ResponseBody
	private ResponseEntity<Object> list(@PathVariable("idDisposizione") Integer idDisposizione, HttpServletRequest request){
		try {
			setRequest(request);
			if (getUserData()==null)
				return new  ResponseEntity<Object>(HttpStatus.UNAUTHORIZED);
			else {
				return new ResponseEntity<Object> (logVariazioniDao.listVariazioni(idDisposizione), HttpStatus.OK);
			}	
		} catch(Exception ex) {
			ex.printStackTrace();
			Logger.getRootLogger().error(ex);
			return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}
	
	@RequestMapping(value="/{idDisposizione}", method=RequestMethod.POST)
	@ResponseBody
	private ResponseEntity<Object> save(
				@PathVariable("idDisposizione") Integer idDisposizione,
				@RequestBody List<LogVariazioniBean> logModificheDisposizioni, 
				HttpServletRequest request) {
		try{
			setRequest(request);
			if (getUserData()==null)
				return new  ResponseEntity<Object>(HttpStatus.UNAUTHORIZED);
			else {
				AppVariables  appVariables =  (AppVariables) getSessionAttribute("appVariables");
				try {
					logVariazioniDao.saveAll(appVariables.getUserId(),appVariables.getDenominazioneUtente(), idDisposizione, logModificheDisposizioni);
					return new ResponseEntity<Object>(HttpStatus.OK);
				} catch (Exception ex) {
					return new ResponseEntity<Object>(ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
				}
					
			}
		} catch(Exception ex) {
			ex.printStackTrace();
			Logger.getRootLogger().error(ex);
			return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}
}
