/*
 * Created on 21 Jul 2015 ( Time 15:00:08 )
 * Generated by Telosys Tools Generator ( version 2.1.1 )
 */
package com.abm.mainet.common.master.ui.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import com.abm.mainet.common.constant.MainetConstants;
import com.abm.mainet.common.constant.MainetConstants.FormMode;
import com.abm.mainet.common.master.dto.TbCustbanks;
import com.abm.mainet.common.master.dto.TbCustbanksMas;
import com.abm.mainet.common.master.service.TbCustbanksMasService;
import com.abm.mainet.common.master.service.TbCustbanksService;
import com.abm.mainet.common.master.ui.model.TbCustbanksMasResponse;
import com.abm.mainet.common.ui.controller.telosys.AbstractController;
import com.abm.mainet.common.utility.Message;
import com.abm.mainet.common.utility.MessageType;
import com.abm.mainet.common.utility.UserSession;

//--- Entities
//--- Services
//--- Common classes

/**
 * Spring MVC controller for 'TbCustbanksMas' management.
 */
@Controller
@RequestMapping("/CustbanksMaster.html")
public class TbCustbanksMasController extends AbstractController {

    // --- Variables names ( to be used in JSP with Expression Language )
    private static final String MAIN_ENTITY_NAME = "tbCustbanksMas";
    private static final String CHILD_ENTITY_NAME = "tbCustbanks";
    private static final String MAIN_LIST_NAME = "list";

    // --- JSP pages names ( View name in the MVC model )
    private static final String JSP_FORM = "tbCustbanksMas/form";
    private static final String JSP_LIST = "tbCustbanksMas/list";
    private static final String JSP_CHILD_FORM = "tbCustbanks/form";

    // --- SAVE ACTION ( in the HTML form )
    private static final String SAVE_ACTION_CREATE = "CustbanksMaster.html?create";
    private static final String SAVE_ACTION_UPDATE = "CustbanksMaster.html?update";

    // --- Main entity service
    @Resource
    private TbCustbanksMasService tbCustbanksMasService; // Injected by Spring
    // --- Other service(s)
    @Resource
    private TbCustbanksService tbCustbanksService;

    List<TbCustbanks> custbanksList = new ArrayList<>();

    TbCustbanksMas custbanksMasTemp;

    // --------------------------------------------------------------------------------------
    /**
     * Default constructor
     */
    public TbCustbanksMasController() {
        super(TbCustbanksMasController.class, MAIN_ENTITY_NAME);
        log("TbCustbanksMasController created.");
    }

    // --------------------------------------------------------------------------------------
    // Spring MVC model management
    // --------------------------------------------------------------------------------------

    /**
     * Populates the Spring MVC model with the given entity and eventually other useful data
     * @param model
     * @param tbCustbanksMas
     */
    private void populateModel(final Model model, final TbCustbanksMas tbCustbanksMas, final FormMode formMode) {
        // --- Main entity
        model.addAttribute(MAIN_ENTITY_NAME, tbCustbanksMas);
        model.addAttribute(MainetConstants.CommonConstants.COMMAND, tbCustbanksMas);
        if (formMode == FormMode.CREATE) {
            model.addAttribute(MODE, MODE_CREATE); // The form is in "create" mode
            model.addAttribute(SAVE_ACTION, SAVE_ACTION_CREATE);
            // --- Other data useful in this screen in "create" mode (all fields)
        } else if (formMode == FormMode.UPDATE) {
            model.addAttribute(MODE, MODE_UPDATE); // The form is in "update" mode
            model.addAttribute(SAVE_ACTION, SAVE_ACTION_UPDATE);
            // --- Other data useful in this screen in "update" mode (only non-pk fields)
        }
    }

    private void populateChildModel(final Model model, final TbCustbanks tbCustbanks, final FormMode formMode) {
        // --- Main entity
        model.addAttribute(CHILD_ENTITY_NAME, tbCustbanks);
        model.addAttribute(MainetConstants.CommonConstants.COMMAND, tbCustbanks);
        if (formMode == FormMode.CREATE) {
            model.addAttribute(MODE, MODE_CREATE); // The form is in "create" mode
            model.addAttribute(SAVE_ACTION, SAVE_ACTION_CREATE);
            // --- Other data useful in this screen in "create" mode (all fields)
        } else if (formMode == FormMode.UPDATE) {
            model.addAttribute(MODE, MODE_UPDATE); // The form is in "update" mode
            model.addAttribute(SAVE_ACTION, SAVE_ACTION_UPDATE);
            // --- Other data useful in this screen in "update" mode (only non-pk fields)
        }
    }

    // --------------------------------------------------------------------------------------
    // Request mapping
    // --------------------------------------------------------------------------------------
    /**
     * Shows a list with all the occurrences of TbCustbanksMas found in the database
     * @param model Spring MVC model
     * @return
     */
    @RequestMapping()
    public String list(final Model model) {
        log("Action 'list'");
        custbanksList = new ArrayList<>();
        return JSP_LIST;
    }

    @RequestMapping(params = "getGridData")
    public @ResponseBody TbCustbanksMasResponse gridData(final HttpServletRequest request, final Model model) {
        log("Action 'Get grid Data'");

        final TbCustbanksMasResponse response = new TbCustbanksMasResponse();

        final int page = Integer.parseInt(request.getParameter(MainetConstants.CommonConstants.PAGE));

        final List<TbCustbanksMas> list = tbCustbanksMasService.findAll();

        response.setRows(list);
        response.setTotal(list.size());
        response.setRecords(list.size());
        response.setPage(page);

        model.addAttribute(MAIN_LIST_NAME, list);

        return response;
    }

    /**
     * Shows a form page in order to create a new TbCustbanksMas
     * @param model Spring MVC model
     * @return
     */
    @RequestMapping(params = "form")
    public String formForCreate(final Model model) {
        log("Action 'formForCreate'");
        // --- Populates the model with a new instance
        final TbCustbanksMas tbCustbanksMas = new TbCustbanksMas();
        populateModel(model, tbCustbanksMas, FormMode.CREATE);
        return JSP_FORM;
    }

    //

    @RequestMapping(params = "addChildForm")
    public String addChildForm(final Model model, @RequestParam("cmBankname") final String cmBankname) {
        log("Action 'formForAddChildData'");
        // --- Populates the model with a new instance
        final TbCustbanks tbCustbanks = new TbCustbanks();
        tbCustbanks.setCbBankname(cmBankname);
        tbCustbanks.setFormMode(FormMode.CREATE.toString());

        populateChildModel(model, tbCustbanks, FormMode.CREATE);
        return JSP_CHILD_FORM;
    }

    @RequestMapping(params = "getChildGridData")
    public @ResponseBody TbCustBankResponse getChildGridData(final HttpServletRequest request, final Model model) {
        log("Action 'Get child grid Data'");

        final TbCustBankResponse response = new TbCustBankResponse();

        final int page = Integer.parseInt(request.getParameter(MainetConstants.CommonConstants.PAGE));

        // List<TbCustbanksMas> list = new ArrayList<TbCustbanksMas>();

        response.setRows(custbanksList);
        response.setTotal(custbanksList.size());
        response.setRecords(custbanksList.size());
        response.setPage(page);

        model.addAttribute(MAIN_LIST_NAME, custbanksList);

        return response;
    }

    @RequestMapping(params = "createChildData", method = RequestMethod.POST) // GET or POST
    public @ResponseBody String createChildData(@RequestParam("cbBankcode") final String cbBankcode,
            @RequestParam("cbBranchname") final String cbBranchname, @RequestParam("cbCity") final String cbCity,
            @RequestParam("cbAddress") final String cbAddress, @RequestParam("pgFlag") final String pgFlag,
            @RequestParam("modeId") final String modeId, final Model model, final HttpServletRequest httpServletRequest) {
        log("Action 'create child data'");
        final TbCustbanks tbCustbanks = new TbCustbanks();
        try {
            // if (!bindingResult.hasErrors()) {
            // TbCustbanksMas tbCustbanksMasCreated = tbCustbanksMasService.create(tbCustbanksMas);cbBankcode
            if (!MainetConstants.CommonConstants.EDIT.equals(modeId) && !custbanksList.isEmpty()) {
                for (final TbCustbanks custBank : custbanksList) {
                    if (custBank.getCbBankcode().intValue() == Integer.valueOf(cbBankcode).intValue()) {
                        return "-1";
                    }
                }
            }

            if (MainetConstants.CommonConstants.EDIT.equals(modeId)) {
                for (final TbCustbanks custBank : custbanksList) {
                    if (custBank.getCbBankcode().intValue() == Integer.valueOf(cbBankcode).intValue()) {
                        custBank.setCbBranchname(cbBranchname);
                        custBank.setCbCity(cbCity);
                        custBank.setCbAddress(cbAddress);
                        custBank.setPgFlag(pgFlag);

                        break;
                    }
                }
            } else {
                tbCustbanks.setCbBankcode(Long.valueOf(cbBankcode));
                tbCustbanks.setCbBranchname(cbBranchname);
                tbCustbanks.setCbCity(cbCity);
                tbCustbanks.setCbAddress(cbAddress);
                tbCustbanks.setPgFlag(pgFlag);
                custbanksList.add(tbCustbanks);
            }

            model.addAttribute(CHILD_ENTITY_NAME, tbCustbanks);
            return CHILD_ENTITY_NAME;
            // } else {
            // populateChildModel(model, tbCustbanks, FormMode.CREATE);
            // return JSP_FORM;
            // }
        } catch (final Exception e) {
            log("Action 'create' : Exception - " + e.getMessage());
            messageHelper.addException(model, "tbCustbanksMas.error.create", e);
            populateChildModel(model, tbCustbanks, FormMode.CREATE);
            return JSP_FORM;
        }
    }

    /**
     * Shows a form page in order to update an existing TbCustbanksMas
     * @param model Spring MVC model
     * @param cmBankid primary key element
     * @return
     */
    @RequestMapping(params = "formForUpdate")
    public String formForUpdate(final Model model, @RequestParam("cmBankid") final Long cmBankid) {
        log("Action 'formForUpdate'");
        // --- Search the entity by its primary key and stores it in the model tbCustbanksService
        final TbCustbanksMas tbCustbanksMas = tbCustbanksMasService.findById(cmBankid);
        custbanksMasTemp = tbCustbanksMas;
        custbanksList = tbCustbanksService.findAllByCmBankId(cmBankid);

        tbCustbanksMas.setCustBanksList(custbanksList);

        populateModel(model, tbCustbanksMas, FormMode.UPDATE);
        // populateChildModel(model, tbCustbanks.get(0), FormMode.UPDATE);

        return JSP_FORM;
    }

    /**
     * 'CREATE' action processing. <br>
     * This action is based on the 'Post/Redirect/Get (PRG)' pattern, so it ends by 'http redirect'<br>
     * @param tbCustbanksMas entity to be created
     * @param bindingResult Spring MVC binding result
     * @param model Spring MVC model
     * @param redirectAttributes Spring MVC redirect attributes
     * @param httpServletRequest
     * @return
     */
    @RequestMapping(params = "create", method = RequestMethod.POST) // GET or POST
    public ModelAndView create(@Valid final TbCustbanksMas tbCustbanksMas, final BindingResult bindingResult, final Model model,
            final HttpServletRequest httpServletRequest) {
        log("Action 'create'");
        try {

            tbCustbanksMas.setUserId(UserSession.getCurrent().getEmployee().getEmpId());
            tbCustbanksMas.setLangId(new Long(UserSession.getCurrent().getLanguageId()));
            tbCustbanksMas.setLmoddate(new Date());

            if (!bindingResult.hasErrors()) {

                tbCustbanksMas.setCustBanksList(custbanksList);
                final TbCustbanksMas tbCustbanksMasCreated = tbCustbanksMasService.create(tbCustbanksMas);
                model.addAttribute(MAIN_ENTITY_NAME, tbCustbanksMasCreated);

                // ---
                messageHelper.addMessage(model, new Message(MessageType.SUCCESS, MainetConstants.COMMON_STATUS.SAVE_OK));
                return new ModelAndView(new MappingJackson2JsonView(), MainetConstants.FORM_NAME, MainetConstants.COMMON_STATUS.SUCCESS);
            } else {
                populateModel(model, tbCustbanksMas, FormMode.CREATE);
                return new ModelAndView(JSP_FORM);
            }
        } catch (final Exception e) {
            log("Action 'create' : Exception - " + e.getMessage());
            messageHelper.addException(model, "tbCustbanksMas.error.create", e);
            populateModel(model, tbCustbanksMas, FormMode.CREATE);
            return new ModelAndView(JSP_FORM);
        }
    }

    /**
     * 'UPDATE' action processing. <br>
     * This action is based on the 'Post/Redirect/Get (PRG)' pattern, so it ends by 'http redirect'<br>
     * @param tbCustbanksMas entity to be updated
     * @param bindingResult Spring MVC binding result
     * @param model Spring MVC model
     * @param redirectAttributes Spring MVC redirect attributes
     * @param httpServletRequest
     * @return
     */
    @RequestMapping(params = "update", method = RequestMethod.POST) // GET or POST
    public ModelAndView ModelAndView(@Valid final TbCustbanksMas tbCustbanksMas, final BindingResult bindingResult,
            final Model model,
            final HttpServletRequest httpServletRequest) {
        log("Action 'update'");
        try {
            if (!bindingResult.hasErrors()) {
                // --- Perform database operations
                tbCustbanksMas.setCustBanksList(custbanksList);
                final TbCustbanksMas tbCustbanksMasSaved = tbCustbanksMasService.update(tbCustbanksMas, custbanksMasTemp);
                model.addAttribute(MAIN_ENTITY_NAME, tbCustbanksMasSaved);
                // --- Set the result message
                messageHelper.addMessage(model, new Message(MessageType.SUCCESS, MainetConstants.COMMON_STATUS.SAVE_OK));
                log("Action 'update' : update done - redirect");
                return new ModelAndView(new MappingJackson2JsonView(), MainetConstants.FORM_NAME, MainetConstants.COMMON_STATUS.SUCCESS);
            } else {
                log("Action 'update' : binding errors");
                populateModel(model, tbCustbanksMas, FormMode.UPDATE);
                return new ModelAndView(JSP_FORM);
            }
        } catch (final Exception e) {
            messageHelper.addException(model, "tbCustbanksMas.error.update", e);
            log("Action 'update' : Exception - " + e.getMessage());
            populateModel(model, tbCustbanksMas, FormMode.UPDATE);
            return new ModelAndView(JSP_FORM);
        }
    }

    /**
     * 'DELETE' action processing. <br>
     * This action is based on the 'Post/Redirect/Get (PRG)' pattern, so it ends by 'http redirect'<br>
     * @param redirectAttributes
     * @param cmBankid primary key element
     * @return
     */
    @RequestMapping(params = "deleteRecord") // GET or POST
    public @ResponseBody String delete(@RequestParam("cmBankid") final Long cmBankid) {
        log("Action 'delete'");
        String successMsg = "failure";
        try {
            tbCustbanksMasService.delete(cmBankid);
            successMsg = MainetConstants.COMMON_STATUS.SUCCESS;
        } catch (final Exception e) {
            // messageHelper.addException(redirectAttributes, "tbCustbanksMas.error.delete", e);
        }
        return successMsg;
    }

    @RequestMapping(params = "editChildForm")
    public String editChildForm(final Model model, @RequestParam("bankCode") final Long bankCode) {
        log("Action 'formForAddChildData'");
        // --- Populates the model with a new instance
        TbCustbanks tbCustbanks = new TbCustbanks();

        for (final TbCustbanks custbanks : custbanksList) {
            if (custbanks.getCbBankcode().intValue() == bankCode.intValue()) {
                tbCustbanks = custbanks;
                tbCustbanks.setFormMode(FormMode.EDIT.toString());
                break;
            }
        }
        populateChildModel(model, tbCustbanks, FormMode.EDIT);
        return JSP_CHILD_FORM;
    }

}
