using AsbCloudDb.Model;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApp1
{
    /// <summary>
    /// Split WellDepth to DepthStart and DepthEnd
    /// </summary>
    static class ActionWellOperationsRefactor
    {
        private static DbContextOptions<AsbCloudDbContext> options = new DbContextOptionsBuilder<AsbCloudDbContext>()
                .UseNpgsql("Host=localhost;Database=postgres;Username=postgres;Password=q;Persist Security Info=True")
                .Options;

        public static void Main()
        {
            using var db = new AsbCloudDbContext(options);

            var wellsIds = db.WellOperations
                .Select(o => o.IdWell)
                .Distinct()
                .ToList();
            var transaction = db.Database.BeginTransaction();
            try
            {
                foreach (var idWell in wellsIds)
                {
                    var operations = db.WellOperations
                        .Where(o => o.IdWell == idWell)
                        .OrderBy(o => o.DateStart)
                        .ThenBy(o => o.DepthEnd)
                        .ToList();

                    var operationsPlan = operations.Where(o => o.IdType == 0);
                    RefactorWellOperations(operationsPlan);

                    var operationsFact = operations.Where(o => o.IdType == 1);
                    RefactorWellOperations(operationsFact);

                    db.SaveChanges();
                }
                transaction.Commit();
            }
            catch
            {
                transaction.Rollback();
            }
        }

        private static void RefactorWellOperations(IEnumerable<WellOperation> operations)
        {
            if (!operations.Any())
                return;
            var oi = operations.GetEnumerator();
            oi.MoveNext();
            var pre = oi.Current;
            oi.Current.DepthStart = 0d;
            while (oi.MoveNext())
            {
                oi.Current.DepthStart = pre.DepthEnd;
                pre = oi.Current;
            }
        }
    }
}