// Copyright © Selmo Technology GmbH. All Rights Reserved

using Novus.Shared.Types.Result;
using SelmoStudio.Hmi.Server.Db.Context;
using System.Diagnostics;

namespace SelmoStudio.Hmi.Server.TestSetup.Services
{
    internal class ProcessDataDbTestSetupService : IProcessDataDbTestSetupService
    {
        private readonly ProcessValueDbContext _context;

        public ProcessDataDbTestSetupService(ProcessValueDbContext context)
        {
            _context = context;
        }

        public async Task<OperationResult<string>> CreateProcessValueTableSetup(int countEntries, IEnumerable<Guid> ids)
        {
            using (_context)
            {
                CreateTestTableForProcessValues(ids);
                CreateTestEntriesForProcessValues(countEntries, ids);
                await _context.SaveChangesAsync();
            }

            return OperationResult<string>.Create("");
        }

        public async Task<string> CreateTestTable(IEnumerable<Guid> ids)
        {
            using (_context)
            {
                CreateTestTableForProcessValues(ids);
                await _context.SaveChangesAsync();
            }

            return string.Empty;
        }

        public List<(DateTimeOffset timestamp, float[] values)> GetProcessValues(IEnumerable<Guid> ids)
        {
            List<(DateTimeOffset timestamp, float[] values)> values = new();
            using (_context)
            {
                var idList = ids.ToList();
                //values = _context.GetProcessValues(idList);
            }

            return values;
        }

        private void CreateTestTableForProcessValues(IEnumerable<Guid> ids)
        {
            var idList = ids.ToList();
            //_context.ExecuteCreateHistoryTable(idList);
        }

        public async Task<string> CreateTestInserts(int count, IEnumerable<Guid> ids)
        {
            Stopwatch stopwatch = Stopwatch.StartNew();
            using (_context)
            {
                CreateTestEntriesForProcessValues(count, ids);
                await _context.SaveChangesAsync();
            }

            stopwatch.Stop();
            Console.WriteLine($"Insert {count} process values. " +
                $"Execution Time = {stopwatch.ElapsedMilliseconds} [ms]");

            return string.Empty;
        }

        private void CreateTestEntriesForProcessValues(int count, IEnumerable<Guid> ids)
        {
            var idList = ids.ToList();
            for (int i = 0; i < count; i++)
            {
                _context.ExecuteInsertTestData(idList);
            }
        }
    }
}