﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Threading.Tasks;

using Dapper;

using Microsoft.EntityFrameworkCore;

using Muscularity.Core.Shared;
using Muscularity.Core.Trainees;
using Muscularity.DataAccess.Entities;

using WorkoutLogEntity = Muscularity.DataAccess.Entities.WorkoutLogEntity;

namespace Muscularity.Features.Workouts.SaveWorkoutLog
{
    public class SaveWorkoutLogData : ISaveWorkoutLogData
    {
        public SaveWorkoutLogData(MuscularityDbContext context, IUserSession userSession)
        {
            Context = context;
            UserSession = userSession;
        }

        protected MuscularityDbContext Context { get; private set; }

        protected IUserSession UserSession { get; private set; }

        public async Task SaveWorkoutLogAsync(int workoutId, WorkoutLogEntity workoutLog)
        {
            using(var con = new SqlConnection(Context.ConnectionString))
            {
                try
                {
                    workoutLog.WorkoutLogId = await con.QuerySingleAsync<int>(
                        "trainee.usp_WorkoutLog_Update",
                        new
                        {
                            workoutLogId = workoutLog.WorkoutLogId,
                            weight = workoutLog.Weight,
                            reps = workoutLog.Reps,
                            repsInReserve = workoutLog.RepsInReserve,
                            workoutId,
                            workoutDetailId = workoutLog.WorkoutDetailId,
                            createDate = workoutLog.CreateDate,
                            userAccountId = UserSession.GetCurrentUserId()
                        },
                        commandType: CommandType.StoredProcedure);
                }
                catch(SqlException ex)
                {
                    if (ex.Number == 15)
                    {
                        throw new ResourceNotFoundException("Workout Log not found.");
                    }

                    throw;
                }
            }
        }
    }
}
