/**
 * Multimud Helper.
 * 
 * Copyright (C) 2009 Benjamin Lerman<br>
 * Copyright (C) 2009 Jacques ???
 * 
 * This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package net.ambre.multimud_helper.dao.impl;

import net.ambre.multimud_helper.bean.Nameable;
import net.ambre.multimud_helper.bean.Skill;
import net.ambre.multimud_helper.bean.SkillLevel;
import net.ambre.multimud_helper.bean.TrainedSkill;
import net.ambre.multimud_helper.bean.Trainer;
import net.ambre.multimud_helper.bean.Zone;
import net.ambre.multimud_helper.dao.TrainerDAO;

import org.hibernate.HibernateException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.transaction.annotation.Transactional;

/**
 * Implementation of {@link TrainerDAOImpl}..
 */
public class TrainerDAOImpl extends HibernateDaoSupport implements TrainerDAO {

    /**
     * {@inheritDoc}
     */
    @Transactional
    public Skill getSkill(String skillName) {
        return getNameable(new Skill(), skillName);
    }

    /**
     * {@inheritedDoc}
     */
    public void addSkill(Trainer trainer, Skill skill, SkillLevel minLevel, SkillLevel maxLevel) {
        for (TrainedSkill trainedSkill : trainer.getTrainedSkills()) {
            if (trainedSkill.getSkill().equals(skill)) {
                trainedSkill.setMinLevel(minLevel);
                trainedSkill.setMaxLevel(maxLevel);
                return;
            }
        }
        TrainedSkill trainedSkill = new TrainedSkill();
        trainedSkill.setSkill(skill);
        trainedSkill.setMinLevel(minLevel);
        trainedSkill.setMaxLevel(maxLevel);
        trainer.getTrainedSkills().add(trainedSkill);
    }

    private <T extends Nameable> T getNameable(T nameable, String name) {
        try {
            // This is safe as Session#get must return an object of the given class.
            @SuppressWarnings("unchecked")
            T result = (T) getSession().get(nameable.getClass(), name);
            if (result == null) {
                result = nameable;
                result.setName(name);
                getSession().save(result);
            }
            return result;
        } catch (HibernateException e) {
            throw convertHibernateAccessException(e);
        }
    }

    /**
     * {@inheritedDoc}
     */
    public Zone getZone(String zoneName) {
        return getNameable(new Zone(), zoneName);
    }
}
