using Insight.Agent.Extensions;
using Insight.Agent.Messages;
using Microsoft.Extensions.Logging;
using System.Text.RegularExpressions;

namespace Insight.Agent.Services
{
    public partial class CollectorService
    {
        public List<Session>? GetSessions()
        {
            Logger.LogTrace("GetSessions");

            var sessions = new List<Session>();

            // request data with process
            var output = "w".Bash();

            // linebreak list conversion
            var lines = output.Split(new string[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries).ToList();

            lines = lines.Select(l =>
            {
                return Regex.Replace(l.Trim().Replace("\t", " "), @"[ ]{2,}", " ");
            }).ToList();

            // cleaning
            lines.RemoveRange(0, 2);

            // process list elements
            foreach (var l in lines)
            {
                // split into elements
                var elements = l.Split(Array.Empty<char>(), StringSplitOptions.RemoveEmptyEntries);

                // add user, assign values
                sessions.Add(new Session
                {
                    User = elements.ElementAt(0),
                    //Id = elements.ElementAt(1),
                    Remote = elements.ElementAt(2),
                    //Login = elements.ElementAt(3),
                    //Idle = elements.ElementAt(4)
                });
            }

            return sessions;
        }
    }
}