package org.apache.rave.portal.service.impl;

import org.apache.rave.model.ExcercicesHasTrainingPlan;
import org.apache.rave.model.Serie;
import org.apache.rave.model.TrainingPlan;
import org.apache.rave.portal.repository.ExcercicesHasTrainingPlanRepository;
import org.apache.rave.portal.repository.SerieRepository;
import org.apache.rave.portal.repository.TrainingPlanRepository;
import org.apache.rave.portal.service.TrainingPlanService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collection;

/**
 * Created by fhernandez on 23/09/14.
 */
@Service
public class DefaultTrainingPlanService implements TrainingPlanService {
    private final Logger logger = LoggerFactory.getLogger(DefaultTrainingPlanService.class);
    private final TrainingPlanRepository trainingPlanRepository;
    private final ExcercicesHasTrainingPlanRepository exercisesHasTrainingPlanRepository;
    private final SerieRepository serieRepository;

    @Autowired
    public DefaultTrainingPlanService(TrainingPlanRepository trainingPlanRepository,ExcercicesHasTrainingPlanRepository exercisesHasTrainingPlanRepository,SerieRepository serieRepository) {
        this.trainingPlanRepository = trainingPlanRepository;
        this.exercisesHasTrainingPlanRepository = exercisesHasTrainingPlanRepository;
        this.serieRepository = serieRepository;
    }

    @Override
    @Transactional
    public TrainingPlan getById(Long trainingPlanId) {
        TrainingPlan trainingPlan =trainingPlanRepository.getById(trainingPlanId);
        if(trainingPlan!=null) {
            trainingPlan.getExercisesHasTrainingplans().size();
        }
        return trainingPlan;
    }

    @Transactional
    public TrainingPlan save(TrainingPlan newPlan) {
        Collection<ExcercicesHasTrainingPlan> exerciseList=newPlan.getExercisesHasTrainingplans();
        try {
            if(newPlan.getEntityId()==null) {
                newPlan = trainingPlanRepository.save(newPlan);
            }
            for (ExcercicesHasTrainingPlan exerciseHasTraining : exerciseList) {
                    Serie serie = serieRepository.save(exerciseHasTraining.getSerie());
                    exerciseHasTraining.setSerie(serie);
                    exerciseHasTraining.setSerieId(serie.getEntityId());
                    exerciseHasTraining.setTrainingplanId(newPlan.getEntityId());
                    exerciseHasTraining.setTrainingPlan(newPlan);
            }
            exercisesHasTrainingPlanRepository.saveList(exerciseList);
        }catch(Exception e){
            logger.error("Exception saving plan " + e);
        }
        return newPlan;
    }

    public Collection<TrainingPlan> getByTrainerID(Long trainerId){
        return trainingPlanRepository.getByTrainerID(trainerId);
    }
}
