/*
 * Copyright 2006-2007 Queplix Corp.
 *
 * Licensed under the Queplix Public License, Version 1.1.1 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.queplix.com/solutions/commercial-open-source/queplix-public-license/
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 *
 */

package com.queplix.core.modules.config.utils.db;

import com.queplix.core.error.GenericSystemException;
import com.queplix.core.modules.config.jxb.LocalizedObject;
import com.queplix.core.modules.config.jxb.LocalizedObjectsId;
import com.queplix.core.modules.config.utils.LocalizationDAO;
import com.queplix.core.utils.dao.AbstractDAO;
import com.queplix.core.utils.sql.SqlWrapper;
import com.queplix.core.utils.sql.SqlWrapperFactory;

import java.lang.reflect.Array;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class LocalizationDAOImpl extends AbstractDAO
        implements LocalizationDAO {

    private final static String SQL_DELETE_OBJECTS_KEY = "delete_localization";
    private final static String SQL_SELECT_OBJECTS_KEY = "select_localization";
    private final static String SQL_INSERT_OBJECTS_KEY = "insert_localization";


    protected SqlWrapper sqlWrapper = SqlWrapperFactory.getSqlWrapper();

    /**
     * No javadoc
     *
     * @see LocalizationDAO#loadLocalizedObjects(LocalizedObjectsId)
     */
    @SuppressWarnings("unchecked")
    public <T extends LocalizedObject> T[] loadLocalizedObjects(
            LocalizedObjectsId objectsId, Class<T> actualType) {

        Connection con = null;
        PreparedStatement ps = null;

        try {
            con = sqlWrapper.doConnection();
            ps = sqlWrapper.doPreparedStatement(con, DBRealmManager.getSql(
                    SQL_SELECT_OBJECTS_KEY));

            sqlWrapper.getStringParser().setObject(ps, 1, objectsId.getId());
            sqlWrapper.getIntParser().setObject(ps, 2, objectsId.getType());
            sqlWrapper.getIntParser().setObject(ps, 3,
                    objectsId.getLocalizationType());

            ResultSet rs = sqlWrapper.executeQuery(ps);

            List<T> objects = new ArrayList<T>();
            while(rs.next()) {
                T object = actualType.newInstance();

                object.setLang(sqlWrapper.getStringParser().getValue(rs, 1));
                String content = sqlWrapper.getStringParser().getValue(rs, 2);
                if(content == null) {
                    content = "";
                }
                object.setContent(content);
                objects.add(object);
            }
            return objects.toArray(
                    (T[]) Array.newInstance(actualType, objects.size()));

        } catch (SQLException e) {
            throw new GenericSystemException("SQLException: " + e.getMessage(),
                    e);
        } catch (InstantiationException e) {
            throw new GenericSystemException(
                    "InstantiationException: " + e.getMessage(), e);
        } catch (IllegalAccessException e) {
            throw new GenericSystemException(
                    "IllegalAccessException: " + e.getMessage(), e);
        } finally {
            sqlWrapper.closeConnection(con, ps);
        }
    }

    /**
     * No javadoc
     *
     * @see LocalizationDAO#removeLocalizedObjects(LocalizedObjectsId)
     */
    public int deleteLocalizedObjects(LocalizedObjectsId objectsId) {
        Connection con = null;
        PreparedStatement ps = null;

        try {
            con = sqlWrapper.doConnection();
            ps = sqlWrapper.doPreparedStatement(con, DBRealmManager.getSql(
                    SQL_DELETE_OBJECTS_KEY));

            sqlWrapper.getStringParser().setObject(ps, 1, objectsId.getId());
            sqlWrapper.getIntParser().setObject(ps, 2, objectsId.getType());
            sqlWrapper.getIntParser().setObject(ps, 3,
                    objectsId.getLocalizationType());

            return sqlWrapper.executeUpdate(ps);

        } catch (SQLException ex) {
            throw new GenericSystemException(
                    "SQL exception: " + ex.getMessage(), ex);
        } finally {
            sqlWrapper.closeConnection(con, ps);
        }
    }

    /**
     * No javadoc
     *
     * @see LocalizationDAO#saveLocalizedObjects(LocalizedObjectsId,LocalizedObject[])
     */
    public <T extends LocalizedObject> int saveLocalizedObjects(
            LocalizedObjectsId objectsId, T[] objects) {
        Connection con = null;
        PreparedStatement ps = null;

        try {
            con = sqlWrapper.doConnection();
            ps = sqlWrapper.doPreparedStatement(con, DBRealmManager.getSql(
                    SQL_INSERT_OBJECTS_KEY));

            String id = objectsId.getId();
            Integer localizationType = objectsId.getLocalizationType();
            Integer type = objectsId.getType();

            int updated = 0;
            for(T object : objects) {
                sqlWrapper.getStringParser().setValue(ps, 1, id);
                sqlWrapper.getIntParser().setValue(ps, 2, localizationType);
                sqlWrapper.getIntParser().setValue(ps, 3, type);
                sqlWrapper.getStringParser().setValue(ps, 4, object.getLang());
                sqlWrapper.getStringParser().setValue(ps, 5,
                        object.getContent());

                updated += sqlWrapper.executeUpdate(ps);
            }

            return updated;

        } catch (SQLException ex) {
            throw new GenericSystemException(
                    "Unable save localization info for object="
                            + objectsId + ". SQL exception: " + ex.getMessage(),
                    ex);
        } finally {
            sqlWrapper.closeConnection(con, ps);
        }
    }

}
