<%@ page import="ro.emid.callcenter.db.LittleIncidentAccessDB" %>
<%@ page import="ro.emid.callcenter.db.LucrareAccessDB" %>
<%@ page import="ro.emid.callcenter.db.LucrareProgramataAccessDB" %>
<%@ page import="ro.emid.common.db.ReclamatieAccessDB" %>
<%@ page import="ro.emid.callcenter.obj.*" %>
<%@ page import="ro.emid.common.db.framework.Filter" %>
<%@ page import="ro.emid.common.utils.ObjectUtils" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.LinkedList" %>
<%@ page import="ro.emid.common.types.LucrareProgramata2" %>
<%@ page import="java.text.MessageFormat" %>
<%@ page import="ro.emid.common.constants.ReclamatieConstants" %>
<%@ page import="ro.emid.common.types.Reclamatie" %>
<%@ page import="ro.emid.common.constants.AdresaConstants" %>
<%@ page import="ro.emid.common.types.Adresa" %>
<%@ page import="ro.emid.common.constants.AppConstants" %>
<%@ page import="ro.emid.common.utils.sort.SortData" %>
<%@ page import="ro.emid.common.utils.pagination.PaginationData" %>
<%@ page import="ro.emid.common.utils.sort.SortController" %>
<%@ page import="ro.emid.common.utils.pagination.PaginationController" %>
<%@ page import="ro.emid.common.utils.StringUtils" %>
<%@ page import="ro.emid.common.db.CategoryAccessDB" %>
<%@ page import="ro.emid.common.types.Category" %>
<%@ page import="ro.emid.common.utils.IntervalLucrare" %>
<%@ page import="java.sql.Timestamp" %>


<%
    try {
        String localitate = ObjectUtils.getStringValue(request.getParameter("localitate"));
        String localitate2 = ObjectUtils.getStringValue(request.getParameter("localitate2"));
        String tipArtera = ObjectUtils.getStringValue(request.getParameter("tipArtera"));
        String denumireStrada = ObjectUtils.getStringValue(request.getParameter("strada"));
        String nr = ObjectUtils.getStringValue(request.getParameter("nr"));
        String bloc = ObjectUtils.getStringValue(request.getParameter("bloc"));


        localitate = localitate.trim().toUpperCase();
        localitate2 = localitate2.trim().toUpperCase();
        tipArtera = tipArtera.trim().toUpperCase();
        denumireStrada = denumireStrada.trim().toUpperCase();
        nr = nr.trim().toUpperCase();
        bloc = bloc.trim().toUpperCase();

        final StringBuffer localizareCondition = new StringBuffer("");
        final StringBuffer localizareReclamatieCondition = new StringBuffer();
        if (localitate.length() > 0) {
            localizareCondition.append(" AND UPPER( a." + AdresaConstants.LOCALITATE + ") LIKE '%").append(ro.emid.common.utils.Util.escapeToSql(localitate)).append("%' ");
            localizareReclamatieCondition.append(" AND UPPER( " + ReclamatieConstants.MUNICIPIU + ") LIKE '%").append(ro.emid.common.utils.Util.escapeToSql(localitate)).append("%' ");
        }

        if (localitate2.length() > 0) {
            localizareCondition.append(" AND UPPER( a." + AdresaConstants.SQL_LOCALITATE2 + ") LIKE '%").append(ro.emid.common.utils.Util.escapeToSql(localitate2)).append("%' ");
            localizareReclamatieCondition.append(" AND UPPER( " + ReclamatieConstants.LOCALITATE2 + ") LIKE '%").append(ro.emid.common.utils.Util.escapeToSql(localitate2)).append("%' ");
        }

        if (tipArtera.length() > 0) {
            localizareCondition.append(" AND UPPER( a." + AdresaConstants.TIP_ARTERA + ") LIKE '%").append(ro.emid.common.utils.Util.escapeToSql(tipArtera)).append("%' ");
            localizareReclamatieCondition.append(" AND UPPER( " + ReclamatieConstants.TIP_ARTERA + ") LIKE '%").append(ro.emid.common.utils.Util.escapeToSql(tipArtera)).append("%' ");
        }

        if (denumireStrada.length() > 0) {
            localizareCondition.append(" AND  UPPER( a." + AdresaConstants.DEN_STRADA + ") LIKE '%").append(ro.emid.common.utils.Util.escapeToSql(denumireStrada)).append("%' ");
            localizareReclamatieCondition.append(" AND  UPPER(" + ReclamatieConstants.STRADA + ") LIKE '%").append(ro.emid.common.utils.Util.escapeToSql(denumireStrada)).append("%' ");
        }

        // !!! VERIFICAREA SE OPRESTE PINA LA NIVEL DE STRADA

        if (nr.length() > 0) {
            localizareReclamatieCondition.append(" AND " + ReclamatieConstants.NR + '=').append('\'').append( nr).append('\'');
        }

        final String niceAdresa = tipArtera + ' ' + denumireStrada + (nr.length() > 0 ? ", nr. " + nr : "") + (bloc.length() > 0 ? " , bl. " + bloc : "");

        final StringBuffer responseMessage = new StringBuffer();

        /**
         *  VERIFICARE LUCRARI PROGRAMATE 2
         */
        try{
            final Filter filter = new Filter();

            filter.addStringCriteria( localizareCondition.toString());


            List list = LucrareProgramataAccessDB.verificareAdresa( filter, "NUMAR", "ASC", 0, 100);
            if( list == null ) list = new LinkedList();

            if ( list.size() == 1){
                final LucrareProgramata2 lucrare = (LucrareProgramata2) list.get( 0);
                final long durata = lucrare.getDurataProgramare();

                final String adresaLucrare = getNiceAdresaLucrare( lucrare);
                    responseMessage.append( "Exista o lucrare programata" );

            }else if ( list.size() > 1) {
                responseMessage.append("Exista ").append( list.size()).append(" lucrari programate(2) : ");

                responseMessage.append("<br/>");
            }

        }catch (Throwable th){
            th.printStackTrace();
        }


        /**
         *  VERIFICARE LUCRARI PROGRAMATE
         */
        final Lucrare[] lucrari = LucrareAccessDB.search( localizareCondition.toString());

        if (lucrari.length == 1){
            final Lucrare lucrare = lucrari[ 0];
            final String _niceAdresaLucrare = getNiceAdresaLucrare( lucrare );

            responseMessage.append( MessageFormat.format( "Exista o lucrare programata <b>{0}</b> pe {1} incepand cu data: {2} timp de {3} <br/>", new Object[]{
                    AppConstants.format(lucrare.getNume()),
                    _niceAdresaLucrare,
                    AppConstants.format(lucrare.getDataStart()),
                    lucrare.getDurata() == 1 ? " o ora " : lucrare.getDurata() + " ore"
            }));

        }else if (lucrari.length > 1) {
            responseMessage.append("Exista ").append(lucrari.length).append(" lucrari programate :");
            for (int i = 0; i < lucrari.length; i++) {
                final Lucrare lucrare = lucrari[i];

                final String _niceAdresa = getNiceAdresaLucrare( lucrare);
                responseMessage.append("&nbsp;&nbsp;<li><b>").append( lucrare.getNume()).append("</b> la adresa ")
                        .append( _niceAdresa)
                        .append(" data: ")
                        .append( AppConstants.format(lucrare.getDataStart()))
                        .append(" timp de ")
                        .append(lucrare.getDurata())
                        .append(" ore");
            }
            responseMessage.append("<br/>");
        }

        /**
         * VERIFICARE LITTLE INCIDENTE
         */
        final LittleIncident[] incidente = LittleIncidentAccessDB.getAllx(localizareCondition.toString());
        if (incidente.length == 1) {
            responseMessage.append("Exista un incident")
                    .append(" (")
                    .append(incidente[0].getNume())
                    .append(')')
                    .append(" pe ")
                    .append(niceAdresa)
                    .append(" anuntat pe data: ")
                    .append(AppConstants.format(incidente[0].getDataAnuntare()))
                    .append("<br/>");
        } else if (incidente.length > 1) {
            responseMessage.append("Exista ").append(incidente.length).append(" incidente pe ").append(niceAdresa).append("<br>");
            for (int i = 0; i < incidente.length; i++) {
                final LittleIncident incident = incidente[i];
                responseMessage.append("&nbsp;&nbsp; - ")
                        .append(incident.getNume())
                        .append(", anuntat pe data: ")
                        .append(AppConstants.format(incident.getDataAnuntare()))
                        .append("<br>");
            }
        }


        /**
         * VERIFICARE RECLAMATII ASEMENEA
         */
        final int nrMinimReclamatii = 3;
        final int intervalMinute = 30;

        final Reclamatie[] reclamatii = ReclamatieAccessDB.getReclamatiiAsemenea(localizareReclamatieCondition.toString(), intervalMinute, "ID", "ASC");
        if (reclamatii.length  >= nrMinimReclamatii) {
            responseMessage.append( MessageFormat.format(
                    "Posibil incident sau deranjament colectiv pe {0} ;<br> Exista {1} reclamatii inregistrate in ultimele {2} minute. <br/>",
                    new Object[]{
                        niceAdresa,
                            String.valueOf(reclamatii.length),
                            String.valueOf(intervalMinute)
                    }
            ));
            responseMessage.append(" reclamatiile nr. ");

            for (int i = 0; i < reclamatii.length; i++) {
                final Reclamatie reclamatie = reclamatii[i];
                responseMessage.append( reclamatie.getId()).append(", ");
            }
        }
%>
<respmesg><%=responseMessage%>

    <%  Filter filter = new Filter();
        filter.addStringCriteria( localizareCondition.toString());
        List listutza = LucrareProgramataAccessDB.verificareAdresa( filter, "NUMAR", "ASC", 0, 100);

        if (listutza.size() > 0 ){
        SortData sd = SortController.getSortData(request, "NUMAR", "DESC");
        PaginationData pd = PaginationController.getPaginationData(request, 20);

        List list = new LinkedList();
        for (int i=0; i<listutza.size(); i++)  {
            list.add(LucrareProgramataAccessDB.getById(  ( (LucrareProgramata2)(listutza.get(i) ) ).getId() ));
        }  %>


<TABLE id="lucrari" border=0 cellPadding=2 cellSpacing=1 width="100%" class="gSAPTHEAD" style="BACKGROUND-COLOR: white;">
    <TR noSelect="true">
        <th class="gsapthead"  nowrap width="10">#</th>
        <th class="gsapthead"  nowrap width="40"> Numar </th>

        <th class="gsapthead">Descriere</th>
        <th title="Data programarii lucrarii" class="gsapthead" width="1%" >Data programare</th>
        <th title="Data programarii lucrarii" class="gsapthead" width="1%" >Durata realizarii lucrarii</th>
        <th title="Data programarii lucrarii" class="gsapthead" width="1%" >Durata intreruperii consumatorilor</th>
    </TR>

    <% if( list == null || list.size() == 0 ) { %>
        <tr>
            <td colspan="10">
                Nu exista date ...
            </td>
        </tr>
    <% } else for (int i = 0; i < list.size(); i++) {
            LucrareProgramata2 lp = (LucrareProgramata2) list.get(i);

            String style = "";
            if( lp.isProgramata()){
                style = "background-color:#ffcccc;";
            }else if( lp.isInLucru()){
                style = "background-color: #ffcc00;";
            }else if( lp.isIncheiata()){
                style = "background-color: #ccff99;";
            }
    %>

        <%-- **** pt fiecare linie --%>

        <tr valign="top">

            <td align="center" title="<%=lp.getStatus()%>" style="<%=style%>" ><%=pd.getStartIndex() + i%></td>

            <td align="center">
                <%=lp.getNumar()%>
            </td>


            <td>
                <%=lp.getParametriTitlu()%>
                <div id="adrese<%=lp.getId()%>" style="display: none; padding-left: 20px">
                    <%  List adrese = lp.getAdreseLucrare();
                        if ( adrese == null || adrese.size() == 0){ %>
                            Fara adrese selectate ...;
                    <%  } else for (int j = 0; j < adrese.size(); j++) {
                            Adresa adresa = (Adresa) adrese.get(j);  %>
                            <% String judet = adresa.getJudet(); %>
                            <% if( StringUtils.isZeroLength(judet)){
                                Category s = CategoryAccessDB.getById(lp.getSucursalaId());
                                if( s == null) s = new Category();
                                judet = s.getName();
                            } %>
                            j.<%=StringUtils.getNullSafe( judet, "-")%>,
                            <%=StringUtils.getNullSafe( adresa.getLocalitate(), "-")%>,
                            <%=StringUtils.getNullSafe( adresa.getLocalitate2(), "-")%>,
                            <%=StringUtils.getNullSafe( adresa.getTipArtera(), "-")%>
                            <%=StringUtils.getNullSafe( adresa.getDenStrada(), "-")%>
                            <%=StringUtils.isZeroLength( adresa.getNr()) ? "" : ", nr. " + adresa.getNr() %>
                            <%=StringUtils.isZeroLength( adresa.getBloc()) ? "" : ", bl. " + adresa.getBloc() %>

                            <br/>
                    <%  } %>
                </div>
            </td>

            <td nowrap align="left" style="font-size:12px"
                title="Durata: <%=lp.getDurataProgramare()/60%>h <%=lp.getDurataProgramare()%60%>m">
                <%
                    List intervaleProgramare = new LinkedList();

                    IntervalLucrare ilDefault = new IntervalLucrare();
                    ilDefault.setDataStart( lp.getDataProgramataStart());
                    ilDefault.setDataStop( lp.getDataProgramataStop());
                    intervaleProgramare.add( ilDefault);

                    if( lp.getCountIntervaleProgramare() > 0){
                        List _intervale = LucrareProgramataAccessDB.getIntervaleProgramare( lp.getId());
                        if( _intervale != null && _intervale.size() > 0){
                            intervaleProgramare.addAll( _intervale);
                        }
                    }

                    for (int j = 0; j < intervaleProgramare.size(); j++) {
                    IntervalLucrare il = (IntervalLucrare) intervaleProgramare.get(j);
                    long difZile = ( il.getDataStop().getTime() - il.getDataStart().getTime() ) / ( 1000 * 60 * 60 * 24);

                    if( j >= 1){ %> <br/> <% }%>
                    <%if( difZile == 0){ %>
                        <%=AppConstants.formatDate( il.getDataStart())%>
                        &nbsp;[<%=AppConstants.formatOraMinute( il.getDataStart())%> - <%=AppConstants.formatOraMinute( il.getDataStop())%>]
                    <% } else {%>
                        [<%=AppConstants.format( il.getDataStart())%> - <%=AppConstants.format( il.getDataStop())%>]
                    <% } %>
                <% } %>
            </td>

            <td nowrap class="style1" style="font-size:12px" title="Durata lucrare: <%=lp.getDurataLucrare()/60%>h <%=lp.getDurataLucrare()%60%>m">
                <%
                    List intervaleLucrare = new LinkedList();

                    IntervalLucrare i2Default = new IntervalLucrare();
                    i2Default.setDataStart( lp.getDataLucrareStart());
                    i2Default.setDataStop( lp.getDataLucrareStop());
                    intervaleLucrare.add( i2Default);

                    if( lp.getCountIntervaleLucrare() > 0){
                        List _intervale = LucrareProgramataAccessDB.getIntervaleLucrare( lp.getId());

                        for (int idx=0; idx<_intervale.size(); idx++)  {
                            if( ( (IntervalLucrare)_intervale.get(idx)).getTip().equals("IL")){
                                intervaleLucrare.add(_intervale.get(idx));
                            }
                        }
                    }

                 for (int j = 0; j < intervaleLucrare.size(); j++) {

                    IntervalLucrare il = (IntervalLucrare) intervaleLucrare.get(j);
                    if( il.getDataStart() != null && il.getDataStop() != null){

                    long difZile = ( il.getDataStop().getTime() - il.getDataStart().getTime() ) / ( 1000 * 60 * 60 * 24);
                       if( j >= 1){ %> <br/> <% }%>
                <% if( difZile == 0){ %>
                <%=AppConstants.formatDate( il.getDataStart())%>
                &nbsp;[<%=AppConstants.formatOraMinute( il.getDataStart())%> - <%=AppConstants.formatOraMinute( il.getDataStop())%>]
                <% } else {%>
                <% if ( il.getDataStart().before(new Timestamp(new java.util.Date().getTime())) &&
                il.getDataStop().after(new Timestamp(new java.util.Date().getTime())) ){ %> <b> <%}%>
                [<%=AppConstants.format( il.getDataStart())%> - <%=AppConstants.format( il.getDataStop())%>]
                <% if ( il.getDataStart().before(new Timestamp(new java.util.Date().getTime())) &&
                il.getDataStop().after(new Timestamp(new java.util.Date().getTime())) ){ %> </b> <%}%>
                <% } %>
                <% } else{ %>
                -
                <% } %>
                <% } %>

            </td>

            <td nowrap class="style1" style="font-size:12px" title="Durata lucrare: <%=lp.getDurataLucrare()/60%>h <%=lp.getDurataLucrare()%60%>m">
                <%
                    List intervaleIntreruperi = new LinkedList();

                    IntervalLucrare i3Default = new IntervalLucrare();
                    i3Default.setDataStart(lp.getDataIntrerupereStart());
                    i3Default.setDataStop( lp.getDataIntrerupereStop());
                    intervaleIntreruperi.add( i3Default);

                    if( lp.getCountIntervaleLucrare() > 0){
                        List _intervale = LucrareProgramataAccessDB.getIntervaleLucrare( lp.getId());

                        for (int idx=0; idx<_intervale.size(); idx++)  {
                            if( ( (IntervalLucrare)_intervale.get(idx)).getTip().equals("II")){
                                intervaleIntreruperi.add(_intervale.get(idx));
                            }
                        }
                    }

                    for (int j = 0; j < intervaleIntreruperi.size(); j++) {
                        IntervalLucrare il = (IntervalLucrare) intervaleIntreruperi.get(j);

                        if( il.getDataStart() != null && il.getDataStop() != null){

                            long difZile = ( il.getDataStop().getTime() - il.getDataStart().getTime() ) / ( 1000 * 60 * 60 * 24);
                            if( j >= 1){ %> <br/> <% }%>
                <% if( difZile == 0){ %>
                <%=AppConstants.formatDate( il.getDataStart())%>
                &nbsp;[<%=AppConstants.formatOraMinute( il.getDataStart())%> - <%=AppConstants.formatOraMinute( il.getDataStop())%>]
                <% } else {%>
                <% if ( il.getDataStart().before(new Timestamp(new java.util.Date().getTime())) &&
                        il.getDataStop().after(new Timestamp(new java.util.Date().getTime())) ){ %> <b> <%}%>
                [<%=AppConstants.format( il.getDataStart())%> - <%=AppConstants.format( il.getDataStop())%>]
                <% if ( il.getDataStart().before(new Timestamp(new java.util.Date().getTime())) &&
                        il.getDataStop().after(new Timestamp(new java.util.Date().getTime())) ){ %> </b> <%}%>
                <% } %>
                <% } else{ %>
                -
                <% } %>
                <% } %>

            </td>

        </tr>
    <tr>
        <td style="border-bottom: thin solid #E6DFDF" colspan="6"> &nbsp;</td>
    </tr>


    <% } %>

</TABLE>
<% } else {}%>


</respmesg>
<%} catch (Throwable t) {
    t.printStackTrace();
}%>


<%!
    private String getNiceAdresaLucrare( final Lucrare lucrare){

        final StringBuffer niceAdresa = new StringBuffer();

        final List listAdrese = lucrare.getAdreseAsList();
        if( listAdrese == null || listAdrese.size()== 0) return "[lucrare fara adresa]";

        for (int i = 0; i < listAdrese.size(); i++) {
            final Adresa adresa = (Adresa) listAdrese.get(i);
            if( i > 0){ niceAdresa.append(", ");}
            niceAdresa.append( getNiceAdresa( adresa));
        }

        return niceAdresa.toString();
    }

    private String getNiceAdresaLucrare( final LucrareProgramata2 lucrare ){

        final StringBuffer niceAdresa = new StringBuffer();

        final List listAdrese = lucrare.getAdreseLucrare();
        if( listAdrese == null || listAdrese.size() == 0) return "[lucrare fara adresa]";

        for (int i = 0; i < listAdrese.size(); i++) {
            final Adresa adresa = (Adresa) listAdrese.get(i);
            if( i > 0){ niceAdresa.append(", ");}
            niceAdresa.append( getNiceAdresa( adresa));
        }

        return niceAdresa.toString();
    }

    private StringBuffer getNiceAdresa(final Adresa adresa){
        final StringBuffer niceAdresa = new StringBuffer();
        niceAdresa.append( adresa.getTipArtera())
                .append(' ')
                .append( adresa.getDenStrada());

            if( adresa.getNr() != null && adresa.getNr().length() > 0){
                niceAdresa.append(", nr. ").append( adresa.getNr());
            }

            if( adresa.getBloc() != null && adresa.getBloc().length() > 0){
                niceAdresa.append(", bl. ").append( adresa.getBloc());
            }


        return niceAdresa;
    }
%>