using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using ModelsLib;
using System.IO;


public class PhotoService
{
    private readonly IDbContextFactory<PhotoShareDbContext> _factory;
    private readonly IWebHostEnvironment _env;

    public PhotoService(IDbContextFactory<PhotoShareDbContext> factory, IWebHostEnvironment env)
    {
        _factory = factory;
        _env = env;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="IdShooting"></param>
    /// <param name="isSelected">Si true alors post traitement donc chargement du dossier export du dossier du shooting</param>
    /// <returns></returns>
    public List<string> LireContenu(string IdShooting, bool isSelected = false)
    {
        string path = "Photos/" + IdShooting;
        if (isSelected)
        {
            path = path + "/export";
        }
        var photosPath = Path.Combine(_env.WebRootPath, path);
        List<string> resultPathsAllPhotos = new List<string>();


        if (Directory.Exists(photosPath))
        {
            var files = Directory.GetFiles(photosPath, "*.jpg");

            foreach (var file in files)
            {
                var fullPath = file; // ton chemin complet

                var relativePath = Path.GetRelativePath(_env.WebRootPath, fullPath);
                resultPathsAllPhotos.Add(relativePath);
            }
        }

        return resultPathsAllPhotos;
    }

    public ShootingData GetInfosShooting(string idShooting)
    {
        using var db = _factory.CreateDbContext();

        return db.ShootingDb.Where(s => s.Key == idShooting).FirstOrDefault();
    }

    public async Task AddShootingInfoPerDefault(string idShooting)
    {
        await using var db = _factory.CreateDbContext();

        db.ShootingDb.Add(
            new ShootingData(idShooting, false, 20, DateTime.UtcNow, "")
        );

        await db.SaveChangesAsync();
    }

    public async Task UpdateShootingInfo(ShootingData shootingData)
    {
        using var db = _factory.CreateDbContext();

        var entity = await db.ShootingDb.FirstOrDefaultAsync(x => x.Key == shootingData.Key);

        if (entity != null)
        {
            entity.IsPhotosSelected = true;

            await db.SaveChangesAsync();
        }
    }

}
