//******************************************************************************************************
//  Common.cs - Gbtc
//
//  Copyright © 2026, Grid Protection Alliance.  All Rights Reserved.
//
//  Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See
//  the NOTICE file distributed with this work for additional information regarding copyright ownership.
//  The GPA licenses this file to you under the MIT License (MIT), the "License"; you may not use this
//  file except in compliance with the License. You may obtain a copy of the License at:
//
//      http://opensource.org/licenses/MIT
//
//  Unless agreed to in writing, the subject software distributed under the License is distributed on an
//  "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
//  License for the specific language governing permissions and limitations.
//
//  Code Modification History:
//  ----------------------------------------------------------------------------------------------------
//  02/25/2026 - J. Ritchie Carroll
//       Generated original version of source code.
//
//******************************************************************************************************

using System.Text;
using System.Text.RegularExpressions;

namespace DNP3ConfigLoader;

public static class Common
{
    /// <summary>
    /// Gets a clean version of the given value by removing characters that are
    /// invalid in a time-series framework identifier, replacing spaces with
    /// underscores, and converting value to uppercase.
    /// </summary>
    /// <param name="value">The value to be cleaned.</param>
    /// <returns>The cleaned identifier.</returns>
    public static string GetCleanIdentifier(string value)
    {
        string cleanValue = value.Replace(" ", "_").ToUpperInvariant();
        return Regex.Replace(cleanValue, @"[^A-Z0-9\-!_\.@#\$]+", "");
    }


    /// <summary>
    /// Parses a CSV line into an array of fields, properly handling quoted fields
    /// that may contain commas and escaped double quotes.
    /// </summary>
    /// <param name="line">The CSV line to parse.</param>
    /// <returns>An array of parsed field values from the CSV line.</returns>
    public static string[] ParseCSVLine(string line)
    {
        List<string> fields = [];
        bool inQuotes = false;
        bool fieldHasQuotes = false;
        StringBuilder fieldBuilder = new();

        for (int i = 0; i < line.Length; i++)
        {
            char c = line[i];

            if (inQuotes)
            {
                if (c == '"')
                {
                    // Peek ahead to see if it's an escaped quote (two quotes in a row)
                    if (i + 1 < line.Length && line[i + 1] == '"')
                    {
                        fieldBuilder.Append('"');
                        i++; // Skip second quote
                    }
                    else
                    {
                        inQuotes = false; // End of quoted field
                    }
                }
                else
                {
                    fieldBuilder.Append(c);
                }
            }
            else
            {
                switch (c)
                {
                    case ',':
                        fields.Add(fieldHasQuotes ? fieldBuilder.ToString() : fieldBuilder.ToString().Trim());
                        fieldBuilder.Clear();
                        fieldHasQuotes = false;
                        break;
                    case '"':
                        inQuotes = true;
                        fieldHasQuotes = true;
                        break;
                    default:
                        fieldBuilder.Append(c);
                        break;
                }
            }
        }

        // Add last field
        fields.Add(fieldHasQuotes ? fieldBuilder.ToString() : fieldBuilder.ToString().Trim());

        return fields.ToArray();
    }
}