using System.IO.Compression;
using System.IO;
using System;
using System.Threading.Tasks;
using System.Linq;
using System.Collections.Generic;
using Discord.WebSocket;
using PluginManager.Items;
namespace PluginManager.Others
{
public static class Functions
{
///
/// The location for the Resources folder
///
public static readonly string dataFolder = @"./Data/Resources/";
///
/// The location for all logs
///
public static readonly string logFolder = @"./Output/Logs/";
///
/// The location for all errors
///
public static readonly string errFolder = @"./Output/Errors/";
///
/// The location for all languages
///
public static readonly string langFolder = @"./Data/Languages/";
///
/// Archives folder
///
public static readonly string pakFolder = @"./Data/Resources/PAKS/";
///
/// The mark that the line is a comment
///
private static readonly char commentMark = '#';
///
/// Read data from file
///
/// File name
/// Setting name
/// Separator between setting key code and its value
/// The value of the specified setting key code in the specified file (STRING)
public static string? readCodeFromFile(string fileName, string Code, char separator)
=> File.ReadAllLines(fileName)
.Where(p => p.StartsWith(Code) && !p.StartsWith(commentMark.ToString()))
.First().Split(separator)[1] ?? null;
///
/// Read data from a file that is inside an archive (ZIP format)
///
/// The file name that is inside the archive or its full path
/// The archive location from the PAKs folder
/// A string that represents the content of the file or null if the file does not exists or it has no content
public static async Task ReadFromPakAsync(string FileName, string archFile)
{
archFile = pakFolder + archFile;
Directory.CreateDirectory(pakFolder);
if (!File.Exists(archFile))
{
throw new Exception("Failed to load file !");
}
string? textValue = null;
var fs = new FileStream(archFile, FileMode.Open);
var zip = new ZipArchive(fs, ZipArchiveMode.Read);
foreach (var entry in zip.Entries)
{
if (entry.Name == FileName || entry.FullName == FileName)
{
Stream s = entry.Open();
StreamReader reader = new StreamReader(s);
textValue = await reader.ReadToEndAsync();
reader.Close();
s.Close();
fs.Close();
break;
}
}
return textValue;
}
///
/// Write logs to file
///
/// The message to be wrote
public static void WriteLogFile(string LogMessage)
{
string logsPath = logFolder + "Log.txt";
if (!Directory.Exists(logFolder))
Directory.CreateDirectory(logFolder);
File.AppendAllText(logsPath, LogMessage + " \n");
}
///
/// Write error to file
///
/// The message to be wrote
public static void WriteErrFile(string ErrMessage)
{
string errPath = errFolder + "Error.txt";
if (!Directory.Exists(errFolder))
Directory.CreateDirectory(errFolder);
File.AppendAllText(errPath, ErrMessage + " \n");
}
///
/// Write to settings file
///
/// The settings file path
/// The Key value of the setting
/// The new value of the settings
/// The separator between the key and the value
public static void WriteToSettings(string file, string Code, string newValue, char separator)
{
string[] lines = File.ReadAllLines(file);
File.Delete(file);
bool ok = false;
foreach (var line in lines)
if (line.StartsWith(Code))
{
File.AppendAllText(file, Code + separator + newValue + "\n"); ok = true;
}
else File.AppendAllText(file, line + "\n");
if (!ok)
File.AppendAllText(file, Code + separator + newValue + "\n");
}
///
/// Merge one array of strings into one string
///
/// The array of strings
/// The index from where the merge should start (included)
/// A string built based on the array
public static string MergeStrings(this string[] s, int indexToStart)
{
string r = "";
int len = s.Length;
if (len <= indexToStart) return "";
for (int i = indexToStart; i < len - 1; ++i)
{
r += s[i] + " ";
}
r += s[len - 1];
return r;
}
///
/// Get the Operating system you are runnin on
///
/// An Operating system
public static OperatingSystem GetOperatinSystem()
{
if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows)) return OperatingSystem.WINDOWS;
if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Linux)) return OperatingSystem.LINUX;
if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.OSX)) return OperatingSystem.MAC_OS;
return OperatingSystem.UNKNOWN;
}
public static List GetArguments(SocketMessage message)
{
Command command = new Command(message);
return command.Arguments;
}
///
/// A way to create a table based on input data
///
/// The List of arrays of strings that represent the rows.
public static void FormatAndAlignTable(List data)
{
char tableLine = '-';
char tableCross = '+';
char tableWall = '|';
int[] len = new int[data[0].Length];
foreach (var line in data)
{
for (int i = 0; i < line.Length; i++)
if (line[i].Length > len[i])
len[i] = line[i].Length;
}
foreach (string[] row in data)
{
//Console.Write("\t");
if (row[0][0] == tableLine) Console.Write(tableCross);
else Console.Write(tableWall);
for (int l = 0; l < row.Length; l++)
{
if (row[l][0] == tableLine)
{
for (int i = 0; i < len[l] + 4; ++i)
Console.Write(tableLine);
}
else if (row[l].Length == len[l])
{
Console.Write(" ");
Console.Write(row[l]);
Console.Write(" ");
}
else
{
int lenHalf = row[l].Length / 2;
for (int i = 0; i < ((len[l] + 4) / 2 - lenHalf); ++i)
Console.Write(" ");
Console.Write(row[l]);
for (int i = (len[l] + 4) / 2 + lenHalf + 1; i < len[l] + 4; ++i)
Console.Write(" ");
if (row[l].Length % 2 == 0)
Console.Write(" ");
}
if (row[l][0] == tableLine) Console.Write(tableCross);
else Console.Write(tableWall);
}
Console.WriteLine(); //end line
}
//Obsolite
#region Old Code -> Spacing by the lomgest item in any cell
/*
int maxLen = 0;
foreach (string[] row in data)
foreach (string s in row)
if (s.Length > maxLen)
maxLen = s.Length;
int div = (maxLen + 4) / 2;
foreach (string[] row in data)
{
//Console.Write("\t");
if (row[0] == "-") Console.Write("+");
else Console.Write("|");
foreach (string s in row)
{
if (s == "-")
{
for (int i = 0; i < maxLen + 4; ++i)
Console.Write("-");
}
else if (s.Length == maxLen)
{
Console.Write(" ");
Console.Write(s);
Console.Write(" ");
}
else
{
int lenHalf = s.Length / 2;
for (int i = 0; i < div - lenHalf; ++i)
Console.Write(" ");
Console.Write(s);
for (int i = div + lenHalf + 1; i < maxLen + 4; ++i)
Console.Write(" ");
if (s.Length % 2 == 0)
Console.Write(" ");
}
if (s == "-") Console.Write("+");
else Console.Write("|");
}
Console.WriteLine(); //end line
}*/
#endregion
}
///
/// Write the text using color options( &g-green; &b-blue; &r-red; &c-clear; )
///
///
/// The text
public static void WriteColorText(string text, bool appendNewLine = true)
{
string[] words = text.Split(' ');
Dictionary colors = new Dictionary()
{
{"&g", ConsoleColor.Green },
{"&b", ConsoleColor.Blue },
{"&r", ConsoleColor.Red },
{"&m", ConsoleColor.Magenta },
{"&c", Console.ForegroundColor }
};
foreach (string word in words)
{
if (word.Length >= 2)
{
string prefix = word.Substring(0, 2);
if (colors.ContainsKey(prefix))
Console.ForegroundColor = colors[prefix];
}
string m = word.Replace("&g", "").Replace("&b", "").Replace("&r", "").Replace("&c", "").Replace("&m", "");
Console.Write(m + " ");
}
if (appendNewLine)
Console.Write('\n');
}
///
/// Write setting
///
/// The full path to the setting
/// The new Value
public static void WriteToSettingsFast(string SettingName, string NewValue)
{
string path = dataFolder; // Resources/
string[] args = SettingName.Split('.');
int len = args.Length;
if (len < 2) return;
for (int i = 0; i < len - 2; i++)
path += args[i] + "/";
path += args[len - 2] + ".txt";
WriteToSettings(path, args[len - 1].Replace('_', ' '), NewValue, '=');
}
public static string FromHexToString(string hexString)
{
var bytes = new byte[hexString.Length / 2];
for (var i = 0; i < bytes.Length; i++)
{
bytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
}
return System.Text.Encoding.Unicode.GetString(bytes);
}
public static string ToHexString(string str)
{
var sb = new System.Text.StringBuilder();
var bytes = System.Text.Encoding.Unicode.GetBytes(str);
foreach (var t in bytes)
{
sb.Append(t.ToString("X2"));
}
return sb.ToString();
}
}
}