<%@page import="com.capgemini.framework.common.SettingsHelper" %>
<%@page import="com.capgemini.framework.common.StringHelper" %>
<%@page import="com.capgemini.reports.database.javabean.enumeration.ReportCriteriaEnum" %>
<%@page import="com.capgemini.reports.database.manager.MngSchedulingCriteriaVal" %>
<%@page import="java.util.Map" %>
<%@page import="com.capgemini.framework.common.DateHelper" %>
<%! final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger("com.capgemini.report.template_r23.jsp"); %>
<%
    /*
     * Available request parameters:
     *	"isUpdateReport"       (boolean)             Is this a submission of a NEW report or an UPDATE?
     *	"idReport"             (long)    <Optional>	 Report Id in case of an UPDATE request
     */
    boolean isDevMode = SettingsHelper.isDevMode();
    boolean isUpdate = Boolean.valueOf(request.getParameter("isUpdateReport"));
    Long reportID = isUpdate ? Long.valueOf(request.getParameter("idReport")) : new Long(-1);

    log.info("**********************");
    log.info("isDevMode            = " + isDevMode);
    log.info("isUpdate             = " + isUpdate);
    log.info("reportID             = " + reportID);

    // Default values in each field. May contain nothing / existing values / development values
    String theDefaultGen = "";
    String theDefaultGenMont = "";
    String theDefaultProduct = "";
    String theDefaultDate = DateHelper.getDate();
    String theMonoMulti = "MONO";
    String isSuperModelBOM = Boolean.FALSE.toString();
    String isWithFrozenUnit = Boolean.FALSE.toString();
    String theDefaultUnit = "";
    String theDefaultFromUnit = "";
    String theDefaultFrozenSinceLessThan = "";

    if (isDevMode) { // Devmode default values
        theDefaultGen = "";
        theDefaultGenMont = "24E";
        theDefaultProduct = "30E0";
        theDefaultDate = "01-01-2015";
    }

    if (isUpdate) { // Existing values to reload from DB
        Map<ReportCriteriaEnum, String> theFunctionalCriteriaValues = new MngSchedulingCriteriaVal().getFunctionalMap(reportID);

        theDefaultGen = StringHelper.replaceNullByEmpty(theFunctionalCriteriaValues.get(ReportCriteriaEnum.GENERIC));
        theDefaultGenMont = StringHelper.replaceNullByEmpty(theFunctionalCriteriaValues.get(ReportCriteriaEnum.GENERIC_ASSEMB));
        theDefaultProduct = StringHelper.replaceNullByEmpty(theFunctionalCriteriaValues.get(ReportCriteriaEnum.PRODUCT));
        theDefaultDate = StringHelper.replaceNullByEmpty(theFunctionalCriteriaValues.get(ReportCriteriaEnum.EFFECTIVITY_DATE));
        theMonoMulti = StringHelper.replaceNullByEmpty(theFunctionalCriteriaValues.get(ReportCriteriaEnum.MONO_MULTI));
        isSuperModelBOM   = StringHelper.replaceNullByEmpty( theFunctionalCriteriaValues.get(ReportCriteriaEnum.SUPERMODEL) );
        isWithFrozenUnit = StringHelper.replaceNullByEmpty(theFunctionalCriteriaValues.get(ReportCriteriaEnum.WITH_FROZEN_UNIT));
        theDefaultUnit = StringHelper.replaceNullByEmpty(theFunctionalCriteriaValues.get(ReportCriteriaEnum.UNIT));
        theDefaultFromUnit = StringHelper.replaceNullByEmpty(theFunctionalCriteriaValues.get(ReportCriteriaEnum.FROM_UNIT));
        theDefaultFrozenSinceLessThan = StringHelper.replaceNullByEmpty(theFunctionalCriteriaValues.get(ReportCriteriaEnum.UNITS_FROZEN_SINCE_LESS_THAN));

        log.info("theDefaultGen     = " + theDefaultGen);
        log.info("theDefaultGenMont = " + theDefaultGenMont);
        log.info("theDefaultProduct = " + theDefaultProduct);
        log.info("theDefaultDate    = " + theDefaultDate);
        log.info("theMonoMulti      = " + theMonoMulti);
        log.info("isWithFrozenUnit  = " + isWithFrozenUnit);
        log.info("theDefaultUnit    = " + theDefaultUnit);
        log.info("theDefaultFromUnit  = " + theDefaultFromUnit);
        log.info("theDefaultFrozenSinceLessThan  = " + theDefaultFrozenSinceLessThan);
    }
%>

<!-- HTML, will probably be imported right inside a form -->
<table cellspacing="0" cellpadding="3" border="0">
    <tr>
        <td class="tdFieldTitle" valign="top">Niveau :</td>
        <td>
            <div style="font-size: 12px;">
                <input type="radio" class="radioInput" id="mono" name="mono_multi"
                       value="mono"   <%=(("MONO".equals(theMonoMulti))) ? "checked" : "" %>/> Mono
                <input type="radio" class="radioInput" id="multi" name="mono_multi"
                       value="multi" <%=(!("MONO".equals(theMonoMulti))) ? "checked" : "" %>/> Multi
                <label for ="modellist">Vue model list</label>
                <input type="checkbox" class="checkform" id="modellist" name="modellist" <%=(Boolean.valueOf(isSuperModelBOM) ? "checked" : "") %> />
                <label for ="with_frozen_unit">Avec le(s) unit(s) gel&eacute;(s)</label>
                <input type="checkbox" class="checkform" id="with_frozen_unit" name="with_frozen_unit" <%=(Boolean.valueOf(isWithFrozenUnit) ? "checked" : "") %> />
                <br/>
                <br/>
            </div>
        </td>
    </tr>
    <tr>
        <td class="tdFieldTitle">G&eacute;n&eacute;rique &quot;Vue Technique&quot; :</td>
        <td>
            <input type="text" id="generic" name="generic" value="<%=theDefaultGen%>"/>
        </td>
    </tr>
    <tr>
        <td class="tdFieldTitle">G&eacute;n&eacute;rique &quot;Vue montage&quot; :</td>
        <td>
            <input type="text" id="generic_assemb" name="generic_assemb" value="<%=theDefaultGenMont%>"/>
        </td>
    </tr>
    <tr>
        <td class="tdFieldTitle required">Produit* :</td>
        <td>
            <input type="text" id="product_id" name="product_id" value="<%=theDefaultProduct%>"/>
        </td>
    </tr>
    <tr>
        <td class="tdFieldTitle">Unit :</td>
        <td>
            <input type="text" id="unit" name="unit" value="<%=theDefaultUnit%>"/>
        </td>
        </tr>
    <tr>
    <tr>
        <td class="tdFieldTitle">A partir du Unit :</td>
        <td>
            <input type="text" id="from_unit" name="from_unit" value="<%=theDefaultFromUnit%>"/>
        </td>
    </tr>
    <tr>
        <td class="tdFieldTitle">Units gel&eacute;s il y a moins de :</td>
        <td>
            <input type="text" id="frozen_since_less_than" name="frozen_since_less_than" value="<%=theDefaultFrozenSinceLessThan%>"/>
        </td>
    </tr>
    <tr>
        <td class="tdFieldTitle">Date d'effectivit&eacute; :</td>
        <td>
            <!-- Start calendar definition -->
            <input id="datepicker" type="text" name="datepicker" style="cursor: hand;" value="<%=theDefaultDate%>"/>
            <div class="flow-element">
                <div id="container">
                </div>
            </div> <!-- End calendar definition -->
        </td>
    </tr>
    <tr>
        <td class="tdFieldTitle" colspan="2" style="text-align: center;">
            <br/>
            <div id="loading" style="display: none;">
                <i>Traitement en cours...</i>
                <br/>
                <img src="/kurt-web/ihm/progress.gif" vspace="6" width="129" height="20">
            </div>
        </td>
    </tr>
</table>

<!-- Internal functional Javascript methods (checks etc.) -->
<script type="text/javascript">

    /* Automatic checks before sending the form */
    function checkForm() {
        var isCheckOk = false;
        var isGenericEmpty = isOptionalFieldEmpty("generic");
        var isGenericAssembEmpty = isOptionalFieldEmpty("generic_assemb");
        var isExlusive = XOR(isGenericEmpty, isGenericAssembEmpty);
        var bothEmpty = isGenericEmpty && isGenericAssembEmpty;
        var isSuperModelOk = document.getElementById("modellist").checked;

        var isWithFrozenUnitOK = document.getElementById("with_frozen_unit").checked;
        var isUnitEmpty = isOptionalFieldEmpty("unit");
        var isFromUnitEmpty = isOptionalFieldEmpty("from_unit");
        var isUnitFrozenSinceEmpty = isOptionalFieldEmpty("frozen_since_less_than");
        var isExclusiveUnitFields = TernaryXOR(isUnitEmpty, isFromUnitEmpty, isUnitFrozenSinceEmpty);
        var UnitFieldsAllEmpty = isUnitEmpty & isFromUnitEmpty & isUnitFrozenSinceEmpty;

        var date = new Date();
        var dateStr = ('0' + date.getDate()).slice(-2) + "-" + ('0' + (date.getMonth() + 1)).slice(-2) + "-" + date.getFullYear();
        var isEffectivityDateCurrentDate = document.getElementById("datepicker").value == dateStr;

        if (isMandatoryFieldEmpty("product_id")) {
            parent.Dialog("Erreur", "Veuillez saisir le champ obligatoire : Produit.");
        } else if (!isUnitFrozenSinceEmpty && !isNumber("frozen_since_less_than")) {
            document.getElementById("frozen_since_less_than").focus();
            parent.Dialog("Erreur", "Vous devez saisir un entier dans le champ Units gel&eacute;s il y a moins de.");
        } else if (!isUnitEmpty && !isNumber("unit")) {
            document.getElementById("unit").focus();
            parent.Dialog("Erreur", "Vous devez saisir un entier dans le champ Unit.");
        } else if (!isFromUnitEmpty && !isNumber("from_unit")) {
            document.getElementById("from_unit").focus();
            parent.Dialog("Erreur", "Vous devez saisir un entier dans le champ A partir de Unit.");
        } else {
            if (!(isExclusiveUnitFields || UnitFieldsAllEmpty)) {
                parent.Dialog("Erreur", "Saisir un Unit ou A partir du unit ou Units gel&eacute;s il y a moins de, le ou est exclusif.");
            } else {
                if(!isUnitFrozenSinceEmpty && !isWithFrozenUnitOK) {
                   parent.Dialog("Erreur", "Avec le(s) unit(s) gel&eacute;(s) n'est pas coch&eacute;");
                } else if(isUnitEmpty && !isEffectivityDateCurrentDate){
                   initPickerWithDefaultDate('datepicker', 'container');
                   document.getElementById("datepicker").value = dateStr;
                   parent.Dialog("Erreur", "Date d'effectivit&eacute; n'est modifiable que si le champ Unit est renseign&eacute;.");
                } else {
                    if (isSuperModelOk) {
                        if (bothEmpty){
                            isCheckOk = true;
                        } else {
                            parent.Dialog("Erreur", "Saisir un G&eacute;n&eacute;rique (G&eacute;n&eacute;rique / G&eacute;n&eacute;rique Montage) ou cocher 'Vue Super Model', le ou est exclusif.");
                        }
                    } else {
                        if (!(isExlusive || bothEmpty)) {
                            document.getElementById("generic").focus();
                            parent.Dialog("Erreur", "Saisir un G&eacute;n&eacute;rique ou un G&eacute;n&eacute;rique Montage, le ou est exclusif.");
                        } else {
                            isCheckOk = true;
                        }
                    }
                }
            }
        }
        return isCheckOk;
    }

    /* Execute a XOR operation between 3 boolean values */
    function TernaryXOR(a, b, c) {
        return (!a && b && c) || (a && !b && c) || (a && b && !c);
    }
    function initPickerWithDefaultDate(pickerId, containerId) {
       new Pikaday({
          field : document.getElementById(pickerId),
          firstDay : 1,
          minDate : new Date('2000-01-01'),
          maxDate: new Date('2030-12-31'),
          defaultDate: new Date(),
          yearRange: [2000, 2030],
          bound : true,
          container : document.getElementById(containerId)
       });
    }

    /* Initialize date picker */
    initPickerWithDefaultDate('datepicker', 'container');
</script>
