
using EFCore.BulkExtensions;
using Electricity.Migrator.Entities;
using Electricity.Migrator.Options;
using Microsoft.Extensions.Hosting;

namespace Electricity.Migrator;

internal class MigratorHostedService : IHostedService
{
    private readonly DatabaseContext database;
    private readonly LogFileOption logFileOption;

    public MigratorHostedService(DatabaseContext database, LogFileOption logFileOption)
    {
        this.database = database;
        this.logFileOption = logFileOption;
    }

    public async Task StartAsync(CancellationToken cancellationToken)
    {
        database.ChangeTracker.AutoDetectChangesEnabled = false;
        await database.Database.EnsureCreatedAsync();

        foreach (var directory in Directory.EnumerateDirectories(logFileOption.Path).OrderBy(d => d))
        {
            foreach (var file in Directory.EnumerateFiles($"{logFileOption.Path}/{directory}").OrderBy(f => f))
            {
                var entities = new List<ElectricityLog>();
                foreach (var line in await File.ReadAllLinesAsync(file))
                {
                    entities.Add(ElectricityLog.CreateFromLine(line));

                    if (entities.Count >= 1000)
                    {
                        await database.BulkInsertAsync(entities);
                        entities.Clear();
                    }
                }

                await database.BulkInsertAsync(entities);
            }

            await database.SaveChangesAsync();
        }
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        return Task.CompletedTask;
    }
}