<%@ page import="org.apache.log4j.Logger"%>
<%@ page import="ro.emid.common.utils.ObjectUtils" %>
<%@ page import="ro.emid.common.db.AccessDB" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="ro.emid.common.db.framework.DatabaseException" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.LinkedList" %>
<%@ page import="ro.emid.common.utils.StringUtils" %>
<%@ page import="ro.emid.common.db.DataDB" %>
<%@ page import="ro.emid.common.components.sugest.base.SugestConstants" %>

<%
    class Instalatie{
        private long id;
        private String cod;
        private String denumire;
        private boolean isLF;
        private String tipOb;
        private String tipText;

        public long getId() {
            return id;
        }

        public void setId(final long id) {
            this.id = id;
        }

        public String getCod() {
            return cod;
        }

        public void setCod(final String cod) {
            this.cod = cod;
        }

        public String getDenumire() {
            return denumire;
        }

        public void setDenumire(final String denumire) {
            this.denumire = denumire;
        }

        public boolean isLF() {
            return isLF;
        }

        public void setLF(final boolean LF) {
            isLF = LF;
        }

        public String getTipOb() {
            return tipOb;
        }

        public void setTipOb(final String tipOb) {
            this.tipOb = tipOb;
        }

        public String getTipText() {
            return tipText;
        }

        public void setTipText(final String tipText) {
            this.tipText = tipText;
        }
    }

    final Logger LOG = Logger.getLogger("cautLocalitateResp_jsp");
    final String whatToSearch = StringUtils.getNullSafe( request.getParameter("q"), "").trim().toUpperCase();


    final int beginIndex = ObjectUtils.getIntValue( request.getParameter( SugestConstants.SUGEST_Q_BEGIN_INDEX), 0);
    final int maxCount = ObjectUtils.getIntValue( request.getParameter( SugestConstants.SUGEST_Q_MAX_COUNT), 10);

    LOG.debug(" whatToSearch=" + whatToSearch);
    try {

        final StringBuffer sql = new StringBuffer();
        sql.append(
                "select * from (\n").append(
                        "    select\n").append(
                        "        1 AS IS_LF,").append(
                        "        ID,\n").append(
                        "        COD_LF AS COD_INST,\n").append(
                        "        DESC_LF AS DESC_INST,\n").append(
                        "        TIP_OB,\n" ).append(
                        "        CASE \n" ).append(
                        "            WHEN TIP_OB = 'UTILIT.ST' THEN 'Statie'\n" ).append(
                        "            WHEN TIP_OB LIKE 'LE%' THEN 'Linie'\n" ).append(
                        "            WHEN TIP_OB LIKE 'P%' THEN 'Post'\n" ).append(
                        "            ELSE '-'\n" ).append(
                        "        END AS TIP_TEXT " ).append(
                        "    from lf\n" ).append(
                        "    union all\n" ).append(
                        "    select \n" ).append(
                        "        0 AS IS_LF," ).append(
                        "        ID,\n" ).append(
                        "        NR_EQ AS COD_INST,\n" ).append(
                        "        DESC_EQ AS DESC_INST,\n" ).append(
                        "        TIP_OB,\n" ).append(
                        "        CASE \n" ).append(
                        "            WHEN TIP_OB LIKE 'CEL%' THEN 'Celula'\n" ).append(
                        "            WHEN TIP_OB LIKE 'LE%' THEN 'Derivatie'\n" ).append(
                        "            WHEN TIP_OB LIKE 'BARE%' THEN 'Bara'\n" ).append(
                        "            WHEN TIP_OB LIKE 'TRAFO%' THEN 'Trafo'\n" ).append(
                        "            WHEN (TIP_OB = 'GTN' OR eq.TIP_OB = 'TIF') THEN 'Bobina'\n" ).append(
                        "            ELSE '-'\n" ).append(
                        "        END AS TIP_TEXT " ).append(
                        "    from eq\n" ).append(
                        ") where UPPER( desc_inst) like '%" ).append( whatToSearch ).append( "%'"
        );


        final StringBuffer listSql = new StringBuffer();
        listSql.append("SELECT * FROM (SELECT a.*, ROWNUM AS rn FROM (\n")
                .append(sql).append(") a WHERE ROWNUM <= ").append(beginIndex + maxCount).append(" \n ) WHERE ").append(beginIndex).append(" <= rn");


        final List instalatii = (List) AccessDB.executeSQL(new AccessDB( "Instalatii suggest ...") {
            protected Object doWork() throws SQLException, DatabaseException {
                final List result = new LinkedList();

                createStatementFromString( listSql.toString());

                getResultSetFromQuery();
                while( resultSet.next()){
                    final Instalatie instalatie = new Instalatie();

                    instalatie.setId( resultSet.getLong("ID"));
                    instalatie.setCod(resultSet.getString("COD_INST"));
                    instalatie.setDenumire(resultSet.getString("DESC_INST"));
                    instalatie.setLF(resultSet.getInt("IS_LF") == 1);
                    instalatie.setTipOb(resultSet.getString("TIP_OB"));
                    instalatie.setTipText(resultSet.getString("TIP_TEXT"));

                    result.add( instalatie);
                }

                return result;
            }
        });

        final Long totalCount = (Long) AccessDB.executeSQL(new AccessDB( "Instalatii suggest count ...") {
            protected Object doWork() throws SQLException, DatabaseException {
                Long result = new Long( 0);

                createStatementFromString( "SELECT count(*) FROM (" + sql.toString() + ')');

                getResultSetFromQuery();
                while( resultSet.next()){
                    result = new Long ( resultSet.getLong(1));
                }

                return result;
            }
        });

        LOG.debug("GASIT " + instalatii.size() + " INSTALATII");
%>

<respmesg>
    {
        totalResultCount: <%=totalCount%>,
        list: [
            <% for (int i = 0; i < instalatii.size(); i++) {
                final Instalatie instalatie = (Instalatie) instalatii.get( i); %>
                <%=( i==0 ? "" : ",") %>
                {
                    key : "<%=instalatie.getId()%>",
                    value : "<%=instalatie.getTipText() + " - " + instalatie.getDenumire()%>",
                    tipInstalatie : "<%=DataDB.getTypeFromString(instalatie.getTipOb())%>",
                    isLF : "<%=instalatie.isLF%>"
                }
            <% } %>
        ]
    }
</respmesg>

<%} catch (Throwable t) {
    LOG.error("Eroare get lista municipii", t);
}%>