﻿using DGS.DAL.Models;
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Text;

namespace DGS.DAL.Repository
{
    public class CreateFile : GenerateDiffTypes
    {
        private TableSettings _settings;

        delegate string GenerateValue(Random rnd);
        GenerateValue valueQueue = null;
        public CreateFile(TableSettings settings)
        {
            _settings = settings;
        }

        public void Start()
        {
            var file = FileSingleton.GetInstance();

            using (StreamWriter sw = new StreamWriter(file.FileName))
            {
                //var watch = Stopwatch.StartNew();
                ConcurrentBag<string> list = new ConcurrentBag<string>();

                //TODO спробувати заюзати MemoryStream
                string colNames = "";
                foreach (var column in _settings.Columns)
                    colNames = colNames.Insert(colNames.Length, column.Name + ";");
                sw.WriteLine(colNames);

                WriteToFile(sw);
                //var result = Parallel.For(0, _settings.Count, (s) => NewOne(sw));
                //watch.Stop();
                //var elapseMs = watch.ElapsedMilliseconds;
            }
        }

        private void WriteToFile(StreamWriter sw)
        {
            var str = new StringBuilder();
            var random = new Random();

            GenerateQueueMethods();

            for (int i = 0; i < _settings.Count; i++)
            {
                for (int j = 0; j < _settings.Columns.Count; j++)
                {
                    var listOfColumnMethods = valueQueue.GetInvocationList();
                    var columnValue = listOfColumnMethods[j].DynamicInvoke(random);
                    str.Append($" {columnValue}; ");
                }
                str.AppendLine();
            }
            sw.WriteLine(str);
        }

        private void GenerateQueueMethods()
        {
            for (int i = 0; i < _settings.Columns.Count; i++)
            {
                if (_settings.Columns[i].Type == ColumnType.Date)
                    valueQueue += RandomDay;
                else if (_settings.Columns[i].Type == ColumnType.Number)
                    valueQueue += RandomNumber;
                else if (_settings.Columns[i].Type == ColumnType.Text)
                    valueQueue += RandonText;
                else if (_settings.Columns[i].Type == ColumnType.UserName)
                    valueQueue += RandomUserName;
            }
        }
    }
}
