C#:
// #define SCHEDULE_DEBUG
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using Facepunch;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Oxide.Core;
using Oxide.Core.Libraries.Covalence;
using Oxide.Core.Plugins;
using Oxide.Game.Rust.Cui;
using Oxide.Plugins.WipeScheduleEx;
using UnityEngine;
using UnityEngine.UI;
# if CARBON
using Carbon.Base;
using Carbon.Modules;
# endif
namespace Oxide.Plugins
{
[Info("Wipe Schedule", "Mevent", "2.0.19")]
public class WipeSchedule : RustPlugin
{
#region Fields
[PluginReference] private Plugin ImageLibrary = null, ServerPanel = null, Notify = null, UINotify = null;
public const bool LangRu = false;
private static WipeSchedule Instance;
private const string
Layer = "UI.WipeSchedule",
Command = "command.wipe.schedule",
PermissionUse = "wipeschedule.admin";
private string[] MonthNames =
{
"January", "February", "March", "April", "May", "June", "July", "August", "September", "October",
"November", "December"
};
private static DateTime currentDateTime
{
get
{
#if SCHEDULE_DEBUG
return DateTime.UtcNow.ToLocalTime();
#else
return DateTime.UtcNow.AddHours(Instance?._config?.TimeZone ?? 0);
#endif
}
}
#endregion
#region Configuration
private Configuration _config = Configuration.GetDefaultConfig();
protected override void LoadConfig()
{
base.LoadConfig();
try
{
#if SCHEDULE_DEBUG
LoadDefaultConfig();
#else
_config = Config.ReadObject<Configuration>();
#endif
if (_config == null) throw new Exception();
SaveConfig();
}
catch
{
PrintError("Your configuration file contains an error. Using default configuration values.");
LoadDefaultConfig();
}
}
protected override void SaveConfig()
{
Config.WriteObject(_config);
}
protected override void LoadDefaultConfig()
{
_config = Configuration.GetDefaultConfig();
}
public static Dictionary<string, LangCustom> GetDefaultCustomLang()
{
return new Dictionary<string, LangCustom>
{
["Custom Event"] = new("Событие сервера", "Custom Event"),
["Custom Event Description"] = new("Описание события сервера", "Custom Event Description")
};
}
public class Configuration
{
[JsonProperty(PropertyName = LangRu ? "Работать с Notify?" : "Work with Notify?")]
public bool UseNotify = true;
[JsonProperty(LangRu ? "Команды для открытия календаря" : "Commands to open the calendar",
ObjectCreationHandling = ObjectCreationHandling.Replace)]
public string[] Commands = {"wipe", "wipedata"};
[JsonProperty(LangRu ? "Временная зона" : "Time Zone")]
public int TimeZone = 2;
[JsonProperty(LangRu ? "Свои ключи в переводчик" : "Your keys in the translator")]
public Dictionary<string, LangCustom> CustomLang;
[JsonProperty(LangRu
? "Для какого шаблона серверного меню использовать настройку ГУИ? (V1, V2)"
: "Which server menu template should I use the GUI setting for? (V1, V2)")]
public PatternServerMenu Pattern;
[JsonProperty(LangRu
? "Начинать календарную неделю с воскресенья"
: "Start calendar week on Sunday")]
public bool WeekStartsOnSunday = false;
public Dictionary<string, LangCustom> GetCustomLang()
{
if (CustomLang == null) return GetDefaultCustomLang();
return CustomLang;
}
public static Configuration GetDefaultConfig()
{
return new Configuration
{
TimeZone = 2,
CustomLang = GetDefaultCustomLang(),
Pattern = PatternServerMenu.V1,
WeekStartsOnSunday = false
};
}
}
public struct LangCustom
{
public string ru;
public string en;
public LangCustom(string ru, string en)
{
this.ru = ru;
this.en = en;
}
}
#endregion
#region Localization
private const string
UI_Date = "UI_Date",
UI_Time = "UI_Time",
UI_Repeat_Every = "UI_Repeat_Every",
UI_Color_Picker = "UI_Color_Picker",
UI_Color_Selected = "UI_Color_Selected",
UI_Color_Hex = "UI_Color_Hex",
UI_Color_Alpha = "UI_Color_Alpha",
UI_Days = "UI_Days",
UI_Weeks = "UI_Weeks",
UI_Repeat_On = "UI_Repeat_On",
UI_Apply_For_Everyone = "UI_Apply_For_Everyone",
UI_Month = "UI_Month",
UI_Years = "UI_Years",
UI_BTN_Back = "UI_BTN_Back",
UI_BTN_Next = "UI_BTN_Next",
UI_BTN_Close = "UI_BTN_Close",
UI_Msg_WhatYouGot_Every = "UI_Msg_WhatYouGot_Every",
UI_Msg_OfEvery = "UI_Msg_OfEvery",
UI_BTN_Down = "UI_BTN_Down",
UI_BTN_Up = "UI_BTN_Up",
UI_Input_Default = "UI_Input_Default",
Calendar = "Calendar",
SetupScheduleTitle = "SetupScheduleTitle",
SetupEventTitle = "SetupEventTitle",
NotifySelection = "NotifySelection",
ADD_EVENT_BUTTON = "ADD_EVENT_BUTTON",
DELETE_EVENT_BUTTON = "DELETE_EVENT_BUTTON",
SAVE_EVENT_BUTTON = "SAVE_EVENT_BUTTON",
SwitchEventType = "SwitchEventType",
TitleInputName = "TitleInputName",
TitleInputDescription = "TitleInputDescription",
AddCustomColorEvent = "AddCustomColorEvent",
EnableForChangeDefaultColor = "EnableForChangeDefaultColor",
AddCustomIconEvent = "AddCustomIconEvent",
EnableForChangeDefaultIcon = "EnableForChangeDefaultIcon",
NotifyNotEditTypeSelection = "NotifyNotEditTypeSelection",
SetupSchedule = "SetupSchedule",
ScheduleInfo = "ScheduleInfo",
TitleEditDateTime = "TitleEditDateTime",
TitleSelectedMonths = "SelectedMonths",
TitleEditTime = "TitleEditTime",
TitleEditDate = "TitleEditDate",
TitleSelectedDays = "TitleSelectedDays",
TitleSelectedDaysOfWeek = "TitleSelectedDaysOfWeek",
TitleSelectedNumWeekOfMonth = "TitleSelectedNumWeekOfMonth",
TitleResult = "TitleResult",
Result_month = "Result_month",
Result_not_month = "Result_not_month",
Result_days = "Result_days",
Result_not_days = "Result_not_days",
Result_weeks = "Result_weeks",
Result_not_weeks = "Result_not_weeks",
Result_num_weeks = "Result_num_weeks",
Result_not_num_weeks = "Result_not_num_weeks",
Result_repeat = "Result_repeat",
Result_use = "Result_use",
Result_disable = "Result_disable",
Result_num1 = "Result_num1",
Result_num2 = "Result_num2",
Result_num3 = "Result_num3",
Result_num4 = "Result_num4",
Result_num5 = "Result_num5";
protected override void LoadDefaultMessages()
{
var ru = new Dictionary<string, string>
{
[Calendar] = "КАЛЕНДАРЬ",
[SetupScheduleTitle] = "НАСТРОЙКА РАСПИСАНИЯ СОБЫТИЙ",
[SetupEventTitle] = "НАСТРОЙКА СОБЫТИЯ",
[NotifySelection] = "Выберите событие для настройки или добавьте новое.",
[ADD_EVENT_BUTTON] = "Добавить событие",
[DELETE_EVENT_BUTTON] = "Удалить",
[SAVE_EVENT_BUTTON] = "Сохранить",
[SwitchEventType] = "Выберите тип события",
[TitleInputName] = "Введите название события",
[TitleInputDescription] = "Введите описание события",
[AddCustomColorEvent] = "Введите цвет события в формате HEX (1-6 символ-цвет 7,8-прозрачность)",
[EnableForChangeDefaultColor] =
"Включите, что бы при сохранении установить дефолтный цвет для данного типа событий",
[AddCustomIconEvent] = "Введите ссылку на свое изображение иконки события",
[EnableForChangeDefaultIcon] =
"Включите, что бы при сохранении установить дефолтную иконку для данного типа событий",
[NotifyNotEditTypeSelection] = "Нельзя редактировать этот тип события.",
[SetupSchedule] = "ИЗМЕНИТЬ ИВЕНТЫ",
[ScheduleInfo] =
"ДЛЯ ПОЛУЧЕНИЯ ДОП. ИНФОРМАЦИИ ВВЕДИТЕ КОМАНДУ <b><color=#64A1CF>/info</color></b> В ЧАТЕ",
[DayOfWeek.Sunday.ToString()] = "ВОСКРЕСЕНЬЕ",
[DayOfWeek.Monday.ToString()] = "ПОНЕДЕЛЬНИК",
[DayOfWeek.Tuesday.ToString()] = "ВТОРНИК",
[DayOfWeek.Wednesday.ToString()] = "СРЕДА",
[DayOfWeek.Thursday.ToString()] = "ЧЕТВЕРГ",
[DayOfWeek.Friday.ToString()] = "ПЯТНИЦА",
[DayOfWeek.Saturday.ToString()] = "СУББОТА",
[TypeEvent.GlobalWipe.ToString()] = "Глобальный вайп",
[TypeEvent.WipeMap.ToString()] = "Вайп карты",
[TypeEvent.WipeBlock.ToString()] = "Вайп блок",
[TypeEvent.EventManager.ToString()] = "Глобальное событие",
[TypeEvent.CustomEvent.ToString()] = "Событие",
[TypeEvent.Today.ToString()] = "Сегодня",
[TitleEditDateTime] = "Тип настройки даты",
[TypeSchedule.DateTime.ToString()] = "Один раз",
[TypeSchedule.CustomDate.ToString()] = "Повторять",
[TitleEditTime] = "Время(часы/минуты)",
[TitleEditDate] = "Дата(день/месяц/год)",
[TitleSelectedMonths] = "Укажите месяца для повтора",
[ModeRepeat.None.ToString()] = "Не повторяется",
[ModeRepeat.Days.ToString()] = "Дни",
[ModeRepeat.Weeks.ToString()] = "Недели",
[ModeRepeat.Months.ToString()] = "Месяцы",
[ModeRepeat.Years.ToString()] = "Годы",
[nameof(ModeRepeat)] = "Выберите режим повтора",
[TitleSelectedDays] = "Дни месяца",
[TitleSelectedDaysOfWeek] = "Дни недели",
[TitleSelectedNumWeekOfMonth] = "Укажите интервалы дней недели",
[TitleResult] = "Результат настройки даты события",
[Result_month] = "каждый указанный месяц, ",
[Result_not_month] = "Не выбраны месяца.",
[Result_days] = "в выбранные числа месяца, ",
[Result_not_days] = "Не выбраны числа месяца.",
[Result_weeks] = "в выбранные дни недели, ",
[Result_not_weeks] = "Не выбраны дни недели.",
[Result_num_weeks] = "каждую {0} указанную неделю месяца, ",
[Result_not_num_weeks] = "Не выбран интервал дней недели.",
[Result_repeat] = "Событие повторяется {0} в {1}",
[Result_use] = "Событие состоится {0} в {1}",
[Result_disable] = "Событие отключено",
[Result_num1] = "первую",
[Result_num2] = "вторую",
[Result_num3] = "третью",
[Result_num4] = "четвертую",
[Result_num5] = "пятую",
[MonthNames[0]] = "Январь",
[MonthNames[1]] = "Февраль",
[MonthNames[2]] = "Март",
[MonthNames[3]] = "Апрель",
[MonthNames[4]] = "Май",
[MonthNames[5]] = "Июнь",
[MonthNames[6]] = "Июль",
[MonthNames[7]] = "Август",
[MonthNames[8]] = "Сентябрь",
[MonthNames[9]] = "Октябрь",
[MonthNames[10]] = "Ноябрь",
[MonthNames[11]] = "Декабрь",
[UI_Date] = "ДАТА",
[UI_Time] = "ВРЕМЯ",
[UI_Repeat_Every] = "ПОВТОРЯТЬ КАЖДЫЙ",
[UI_Color_Picker] = "ВЫБОР ЦВЕТА",
[UI_Color_Selected] = "ВЫБРАННЫЙ ЦВЕТ:",
[UI_Color_Hex] = "HEX",
[UI_Color_Alpha] = "ПРОЗРАЧНОСТЬ (0-100)",
[UI_Days] = "ДНИ",
[UI_Weeks] = "НЕДЕЛИ",
[UI_Repeat_On] = "ПОВТОРЯТЬ НА",
[UI_Apply_For_Everyone] = "ПРИМЕНИТЬ ДЛЯ ВСЕХ СОБЫТИЙ ЭТОГО ТИПА",
[UI_Month] = "месяц",
[UI_Years] = "годы",
[UI_BTN_Back] = "<",
[UI_BTN_Next] = ">",
[UI_BTN_Close] = "X",
[UI_Msg_WhatYouGot_Every] = "Что вы получили: Повторять каждый {0}й день.",
[UI_Msg_OfEvery] = "{0} каждый",
[UI_BTN_Down] = "▼",
[UI_BTN_Up] = "▲",
[UI_Input_Default] = "по умолчанию",
};
var en = new Dictionary<string, string>
{
[Calendar] = "CALENDAR",
[SetupScheduleTitle] = "EVENT SCHEDULE SETUP",
[SetupEventTitle] = "EVENT SETUP",
[NotifySelection] = "Select an event to configure or add a new one.",
[ADD_EVENT_BUTTON] = "Add Event",
[DELETE_EVENT_BUTTON] = "Delete",
[SAVE_EVENT_BUTTON] = "Save",
[SwitchEventType] = "Select event type",
[TitleInputName] = "Enter event name",
[TitleInputDescription] = "Enter event description",
[AddCustomColorEvent] = "Enter event color in HEX format (1-6 color symbols, 7,8 - transparency)",
[EnableForChangeDefaultColor] = "Enable to set the default color for this type of events upon saving",
[AddCustomIconEvent] = "Enter the link to your event icon image",
[EnableForChangeDefaultIcon] = "Enable to set the default icon for this type of events upon saving",
[NotifyNotEditTypeSelection] = "This event type cannot be edited.",
[SetupSchedule] = "CHANGE EVENTS",
[ScheduleInfo] = "FOR MORE INFORMATION, TYPE <b><color=#64A1CF>/info</color></b> IN CHAT",
[DayOfWeek.Sunday.ToString()] = "SUNDAY",
[DayOfWeek.Monday.ToString()] = "MONDAY",
[DayOfWeek.Tuesday.ToString()] = "TUESDAY",
[DayOfWeek.Wednesday.ToString()] = "WEDNESDAY",
[DayOfWeek.Thursday.ToString()] = "THURSDAY",
[DayOfWeek.Friday.ToString()] = "FRIDAY",
[DayOfWeek.Saturday.ToString()] = "SATURDAY",
[TypeEvent.GlobalWipe.ToString()] = "Global Wipe",
[TypeEvent.WipeMap.ToString()] = "Map Wipe",
[TypeEvent.WipeBlock.ToString()] = "Block Wipe",
[TypeEvent.EventManager.ToString()] = "Global Event",
[TypeEvent.CustomEvent.ToString()] = "Event",
[TypeEvent.Today.ToString()] = "Today",
[TitleEditDateTime] = "Date Setting Type",
[TypeSchedule.DateTime.ToString()] = "Once",
[TypeSchedule.CustomDate.ToString()] = "Repeat",
[TitleEditTime] = "Time (hours/minutes)",
[TitleEditDate] = "Date (day/month/year)",
[TitleSelectedMonths] = "Specify months for repetition",
[ModeRepeat.None.ToString()] = "Does not repeat",
[ModeRepeat.Days.ToString()] = "Days",
[ModeRepeat.Weeks.ToString()] = "Weeks",
[ModeRepeat.Months.ToString()] = "Months",
[ModeRepeat.Years.ToString()] = "Years",
[nameof(ModeRepeat)] = "Select repeat mode",
[TitleSelectedDays] = "Days of the month",
[TitleSelectedDaysOfWeek] = "Days of the week",
[TitleSelectedNumWeekOfMonth] = "Specify intervals of days of the week",
[TitleResult] = "Event date setup result",
[Result_month] = "every specified month, ",
[Result_not_month] = "No months selected.",
[Result_days] = "on the selected days of the month, ",
[Result_not_days] = "No days of the month selected.",
[Result_weeks] = "on the selected days of the week, ",
[Result_not_weeks] = "No days of the week selected.",
[Result_num_weeks] = "every {0} specified week of the month, ",
[Result_not_num_weeks] = "No interval of days of the week selected.",
[Result_repeat] = "The event repeats {0} on {1}",
[Result_use] = "The event will take place {0} at {1}",
[Result_disable] = "The event is disabled",
[Result_num1] = "first",
[Result_num2] = "second",
[Result_num3] = "third",
[Result_num4] = "fourth",
[Result_num5] = "fifth",
[MonthNames[0]] = MonthNames[0],
[MonthNames[1]] = MonthNames[1],
[MonthNames[2]] = MonthNames[2],
[MonthNames[3]] = MonthNames[3],
[MonthNames[4]] = MonthNames[4],
[MonthNames[5]] = MonthNames[5],
[MonthNames[6]] = MonthNames[6],
[MonthNames[7]] = MonthNames[7],
[MonthNames[8]] = MonthNames[8],
[MonthNames[9]] = MonthNames[9],
[MonthNames[10]] = MonthNames[10],
[MonthNames[11]] = MonthNames[11],
[UI_Date] = "DATE",
[UI_Time] = "TIME",
[UI_Repeat_Every] = "REPEAT EVERY",
[UI_Color_Picker] = "COLOR PICKER",
[UI_Color_Selected] = "Selected color:",
[UI_Color_Hex] = "HEX",
[UI_Color_Alpha] = "Opacity (0-100)",
[UI_Days] = "DAYS",
[UI_Weeks] = "WEEKS",
[UI_Repeat_On] = "REPEAT ON",
[UI_Apply_For_Everyone] = "APPLY AN ICON FOR EVERYONE EVENTS OF THIS TYPE",
[UI_Month] = "month",
[UI_Years] = "years",
[UI_BTN_Back] = "<",
[UI_BTN_Next] = ">",
[UI_BTN_Close] = "X",
[UI_Msg_WhatYouGot_Every] = "What you got: Repeat every {0}th day.",
[UI_Msg_OfEvery] = "{0} of every",
[UI_BTN_Down] = "▼",
[UI_BTN_Up] = "▲",
[UI_Input_Default] = "default",
};
foreach (var custom in _config.GetCustomLang())
if (!string.IsNullOrEmpty(custom.Key) && !string.IsNullOrEmpty(custom.Value.ru) &&
!string.IsNullOrEmpty(custom.Value.en))
{
if (ru.ContainsKey(custom.Key)) ru[custom.Key] = custom.Value.ru;
else ru.TryAdd(custom.Key, custom.Value.ru);
if (en.ContainsKey(custom.Key)) en[custom.Key] = custom.Value.en;
else en.TryAdd(custom.Key, custom.Value.en);
}
lang.RegisterMessages(ru, this, "ru");
lang.RegisterMessages(en, this);
}
private static string GetMessage(string key, string userid = null, params object[] obj)
{
return string.Format(Instance.lang.GetMessage(key, Instance, userid), obj);
}
private string Msg(string playerID, string key, params object[] obj)
{
return string.Format(lang.GetMessage(key, this, playerID), obj);
}
private void Reply(BasePlayer player, string key, params object[] obj)
{
if (player == null) return;
SendReply(player, Msg(player.UserIDString, key, obj));
}
private void Reply(IPlayer player, string key, params object[] obj)
{
player?.Reply(string.Format(lang.GetMessage(key, this, player.Id), obj));
}
private void SendNotify(BasePlayer player, string key, int type, params object[] obj)
{
if (_config.UseNotify && (Notify != null || UINotify != null))
Interface.Oxide.CallHook("SendNotify", player, type, Msg(player.UserIDString, key, obj));
else
Reply(player, key, obj);
}
#endregion
#region Initialization
private void Init()
{
Instance = this;
PlayerUIController.Init();
}
private void OnServerInitialized()
{
FullScreenTransform = new CuiRectTransformComponent
{AnchorMin = "0 0", AnchorMax = "1 1", OffsetMin = "0 0", OffsetMax = "0 0"};
LoadInterfaceUI();
LoadSchedule();
LoadIcons();
LoadColors();
LoadImages();
RegisterPermissions();
RegisterCommands();
}
private void Unload()
{
PlayerUIController.Unload();
Instance = null;
FullScreenTransform = null;
}
#endregion
#region Data
private ScreenInterfaceSetup UIFullScreen;
private UserInterfaceSetup UIMenu;
private Dictionary<TypeEvent, IColor> EventsColors;
private Dictionary<TypeEvent, ImageSettings> IconSetup;
private List<ScheduleToDay> Schedule = new();
private readonly List<ScheduleToDay> ScheduleEventsManager = new();
private string FILE_Schedule = $"{nameof(WipeSchedule)}/Schedule";
private string FILE_IconSetup = $"{nameof(WipeSchedule)}/IconSetup";
private string FILE_EventsColors = $"{nameof(WipeSchedule)}/EventsColors";
private delegate T GetDef<out T>() where T : class;
private void LoadInterfaceUI()
{
#if SCHEDULE_DEBUG
UIMenu = UserInterfaceSetup.GenerateUIMenuV1();
UIFullScreen = UserInterfaceSetup.GenerateFullScreen();
#else
switch (_config.Pattern)
{
case PatternServerMenu.V1:
UIMenu = LoadDateFile($"{nameof(WipeSchedule)}/SetupUI/UIMenuV1",
UserInterfaceSetup.GenerateUIMenuV1);
break;
case PatternServerMenu.V2:
UIMenu = LoadDateFile($"{nameof(WipeSchedule)}/SetupUI/UIMenuV2",
UserInterfaceSetup.GenerateUIMenuV2);
break;
default:
UIMenu = LoadDateFile($"{nameof(WipeSchedule)}/SetupUI/UIMenuV2",
UserInterfaceSetup.GenerateUIMenuV2);
break;
}
UIFullScreen = LoadDateFile($"{nameof(WipeSchedule)}/SetupUI/UIFulScreen",
UserInterfaceSetup.GenerateFullScreen);
#endif
}
private void LoadSchedule()
{
#if SCHEDULE_DEBUG
Schedule = GetDefaultSchedule();
ScheduleEventsManager.Clear();
ScheduleEventsManager.AddRange(GetTestScheduleEvent());
#else
Schedule = LoadDateFile(FILE_Schedule, GetDefaultSchedule);
#endif
}
private void LoadIcons()
{
#if SCHEDULE_DEBUG
IconSetup = GetDefaultIconsEvent();
#else
IconSetup = LoadDateFile(FILE_IconSetup, GetDefaultIconsEvent);
#endif
}
private void LoadColors()
{
#if SCHEDULE_DEBUG
EventsColors = GetDefaultColorsEvent();
#else
EventsColors = LoadDateFile(FILE_EventsColors, GetDefaultColorsEvent);
if (Version == new VersionNumber(2, 0, 9))
if (EventsColors.TryAdd(TypeEvent.Today, new IColor("#00E6FF", 20)))
{
SaveDateFile(FILE_EventsColors, EventsColors);
}
#endif
}
private static void SaveDateFile<T>(string name, T value) where T : class
{
Interface.Oxide.DataFileSystem.WriteObject(name, value);
}
private static T LoadDateFile<T>(string name, GetDef<T> callbackDefault) where T : class
{
T obj = null;
try
{
obj = !Interface.Oxide.DataFileSystem.ExistsDatafile(name) ? callbackDefault.Invoke() : Interface.Oxide.DataFileSystem.ReadObject<T>(name);
}
finally
{
obj ??= callbackDefault.Invoke();
}
SaveDateFile(name, obj);
return obj;
}
private List<ScheduleToDay> GetDefaultSchedule()
{
return new List<ScheduleToDay>
{
new(TypeSchedule.CustomDate, TypeEvent.GlobalWipe, "Global Wipe")
{
CustomDateTimeEvent = new CustomDateTime(
ModeRepeat.Months, 1, 1,
new bool[7] {false, false, false, true, false, false, false}, new MyTime(20, 0), false, false)
},
new(TypeSchedule.CustomDate, TypeEvent.WipeMap, "Wipe Map")
{
CustomDateTimeEvent = new CustomDateTime(
ModeRepeat.Months, 1, 1,
new bool[7] {false, false, false, true, false, false, false}, new MyTime(20, 0), false, false)
},
new(TypeSchedule.CustomDate, TypeEvent.WipeBlock, "Wipe Block")
{
CustomDateTimeEvent = new CustomDateTime(
ModeRepeat.Weeks, 1, 1,
new bool[7] {true, true, false, false, false, false, false}, new MyTime(20, 0), false, false)
},
new(TypeSchedule.CustomDate, TypeEvent.CustomEvent, "Custom Event")
{
Descriptions = "Custom Event Description",
CustomDateTimeEvent = new CustomDateTime(
ModeRepeat.Weeks, 1, 1,
new bool[7] {false, false, true, false, false, false, false}, new MyTime(20, 0), false, false)
}
};
}
#if SCHEDULE_DEBUG
private List<ScheduleToDay> GetTestScheduleEvent()
{
return new()
{
new(TypeSchedule.CustomDate, TypeEvent.EventManager, "EventManager 1")
{
CustomDateTimeEvent =
new CustomDateTime(ModeRepeat.Weeks, 1, 1, new bool[7]{ false, false, false, false, false, true, false },
new MyTime(18, 0), false, false)
},
new(TypeSchedule.CustomDate, TypeEvent.EventManager, "EventManager 2")
{
CustomDateTimeEvent =
new CustomDateTime(ModeRepeat.Weeks, 1, 1, new bool[7]{ false, false, false, false, false, true, false },
new MyTime(18, 0), false, false)
},
};
}
#endif
private Dictionary<TypeEvent, IColor> GetDefaultColorsEvent()
{
return new Dictionary<TypeEvent, IColor>
{
[TypeEvent.GlobalWipe] = new("#E44028", 25),
[TypeEvent.WipeMap] = new("#29e340", 15),
[TypeEvent.WipeBlock] = new("#C8AD1E", 15),
[TypeEvent.EventManager] = new("#9f19a8", 15),
[TypeEvent.CustomEvent] = new("#5870E9", 15),
[TypeEvent.Today] = new("#00E6FF", 20)
};
}
private Dictionary<TypeEvent, ImageSettings> GetDefaultIconsEvent()
{
return new Dictionary<TypeEvent, ImageSettings>
{
[TypeEvent.GlobalWipe] = new()
{
AnchorMin = "0 0", AnchorMax = "1 1", OffsetMin = "0 0", OffsetMax = "0 0",
Color = new IColor("#FFFFFF"), Image = "https://i.ibb.co/mbM7mGQ/2a80d35cd540.png"
},
[TypeEvent.WipeMap] = new()
{
AnchorMin = "0 0", AnchorMax = "1 1", OffsetMin = "0 0", OffsetMax = "0 0",
Color = new IColor("#FFFFFF"), Image = "https://i.ibb.co/mbM7mGQ/2a80d35cd540.png"
},
[TypeEvent.WipeBlock] = new()
{
AnchorMin = "0 0", AnchorMax = "1 1", OffsetMin = "0 0", OffsetMax = "0 0",
Color = new IColor("#FFFFFF"), Image = "https://i.ibb.co/mbM7mGQ/2a80d35cd540.png"
},
[TypeEvent.EventManager] = new()
{
AnchorMin = "0 0", AnchorMax = "1 1", OffsetMin = "0 0", OffsetMax = "0 0",
Color = new IColor("#FFFFFF"), Image = "https://i.ibb.co/mbM7mGQ/2a80d35cd540.png"
},
[TypeEvent.CustomEvent] = new()
{
AnchorMin = "0 0", AnchorMax = "1 1", OffsetMin = "0 0", OffsetMax = "0 0",
Color = new IColor("#FFFFFF"), Image = "https://i.ibb.co/mbM7mGQ/2a80d35cd540.png"
}
};
}
private class ScheduleToDay
{
public TypeSchedule ScheduleType = TypeSchedule.DateTime;
public TypeEvent EventType = TypeEvent.GlobalWipe;
public bool Enable = true;
public string Name = "NameEvent";
public DateTime DateTimeEvent = DateTime.UtcNow;
public CustomDateTime CustomDateTimeEvent;
public string Descriptions = "Description";
public string UrlIcon = "";
public IColor Color;
public ScheduleToDay()
{
}
public ScheduleToDay(TypeSchedule type, TypeEvent @event, string name)
{
ScheduleType = type;
EventType = @event;
Name = name;
}
public bool HasEventOfDay(DateTime dateTime)
{
return Enable && dateTime.Year == DateTimeEvent.Year && dateTime.Month == DateTimeEvent.Month &&
dateTime.Day == DateTimeEvent.Day;
}
private bool HasEventOfMonth(DateTime dateTime)
{
return dateTime.Year == DateTimeEvent.Year && dateTime.Month == DateTimeEvent.Month;
}
public void SetScheduleOfMonth(DateTime startDate, List<ScheduleToDay> list)
{
if (!Enable) return;
if (startDate.Date < new DateTime(DateTimeEvent.Year, DateTimeEvent.Month, 1).Date) return;
var daysInMonth = DateTime.DaysInMonth(startDate.Year, startDate.Month);
switch (CustomDateTimeEvent.Mode)
{
case ModeRepeat.None:
{
list.Add(new ScheduleToDay
{
ScheduleType = TypeSchedule.DateTime, Enable = true, EventType = EventType,
Name = Name, UrlIcon = UrlIcon, Descriptions = Descriptions,
Color = Color,
DateTimeEvent = new DateTime(DateTimeEvent.Year, DateTimeEvent.Month, DateTimeEvent.Day,
CustomDateTimeEvent.Times.Hour, CustomDateTimeEvent.Times.Minute, 0)
});
return;
}
case ModeRepeat.Days:
{
if (CustomDateTimeEvent.DaysInterval < 1) return;
for (var day = 1; day <= daysInMonth; day++)
{
var targetDate = new DateTime(startDate.Year, startDate.Month, day, CustomDateTimeEvent.Times.Hour, CustomDateTimeEvent.Times.Minute, 0);
if (targetDate < DateTimeEvent) continue;
var daysFromStart = targetDate.Subtract(DateTimeEvent).TotalDays;
if (daysFromStart % CustomDateTimeEvent.DaysInterval != 0) continue;
list.Add(new ScheduleToDay
{
ScheduleType = TypeSchedule.DateTime, Enable = true, EventType = EventType,
Name = Name, UrlIcon = UrlIcon, Descriptions = Descriptions,
Color = Color,
DateTimeEvent = targetDate
});
}
return;
}
case ModeRepeat.Weeks:
{
var dateTime1 = new DateTime(startDate.Year, startDate.Month, 1);
for (var i = 0; i < daysInMonth; i++)
{
var newDay = dateTime1.AddDays(i);
var weeks = Mathf.CeilToInt((float) (newDay.Subtract(DateTimeEvent).TotalDays / 7f));
if (CustomDateTimeEvent.DaysInterval > 1 && weeks % CustomDateTimeEvent.DaysInterval != 0)
continue;
if (CustomDateTimeEvent.HasDayOfWeek(newDay.DayOfWeek))
list.Add(new ScheduleToDay
{
ScheduleType = TypeSchedule.DateTime, Enable = true, EventType = EventType,
Name = Name, UrlIcon = UrlIcon, Descriptions = Descriptions,
Color = Color,
DateTimeEvent = new DateTime(startDate.Year, startDate.Month, i + 1,
CustomDateTimeEvent.Times.Hour, CustomDateTimeEvent.Times.Minute, 0)
});
}
return;
}
case ModeRepeat.Months:
{
if (CustomDateTimeEvent.MonthRepeatOnDay)
{
if (CustomDateTimeEvent.DaysInterval > 1)
{
var diff = GetMonthsDifference(new DateTime(DateTimeEvent.Year, DateTimeEvent.Month, 1),
new DateTime(startDate.Year, startDate.Month, 1));
if (diff > 0 && diff % CustomDateTimeEvent.DaysInterval != 0)
return;
}
for (var i = 0; i < daysInMonth; i++)
{
var day = i + 1;
if (day == DateTimeEvent.Day)
list.Add(new ScheduleToDay
{
ScheduleType = TypeSchedule.DateTime, Enable = true, EventType = EventType,
Name = Name, UrlIcon = UrlIcon, Descriptions = Descriptions,
Color = Color,
DateTimeEvent = new DateTime(startDate.Year, startDate.Month, day,
CustomDateTimeEvent.Times.Hour, CustomDateTimeEvent.Times.Minute, 0)
});
}
}
if (CustomDateTimeEvent.MonthRepeatOnDayOfWeek)
{
if (CustomDateTimeEvent.WeeksInterval > 1)
{
var diff = GetMonthsDifference(new DateTime(DateTimeEvent.Year, DateTimeEvent.Month, 1),
new DateTime(startDate.Year, startDate.Month, 1));
if (diff > 0 && diff % CustomDateTimeEvent.WeeksInterval != 0)
return;
}
var dayOfWeek = DateTimeEvent.DayOfWeek;
var weekOfMonth = GetWeekOfMonth(DateTimeEvent);
var firstDayOfMonth = new DateTime(startDate.Year, startDate.Month, 1);
for (var i = 0; i < daysInMonth; i++)
{
var currentDate = firstDayOfMonth.AddDays(i);
var isSecondSunday = currentDate.DayOfWeek == dayOfWeek &&
GetWeekOfMonth(currentDate) == weekOfMonth;
if (isSecondSunday)
list.Add(new ScheduleToDay
{
ScheduleType = TypeSchedule.DateTime, Enable = true, EventType = EventType,
Name = Name, UrlIcon = UrlIcon, Descriptions = Descriptions,
Color = Color,
DateTimeEvent = new DateTime(startDate.Year, startDate.Month, i + 1,
CustomDateTimeEvent.Times.Hour, CustomDateTimeEvent.Times.Minute, 0)
});
}
}
return;
}
case ModeRepeat.Years:
{
if (DateTimeEvent.Month == startDate.Month)
{
var diff = startDate.Year - DateTimeEvent.Year;
if (diff > 0 && diff % CustomDateTimeEvent.DaysInterval != 0)
return;
list.Add(new ScheduleToDay
{
ScheduleType = TypeSchedule.DateTime, Enable = true, EventType = EventType,
Name = Name, UrlIcon = UrlIcon, Descriptions = Descriptions,
Color = Color,
DateTimeEvent = new DateTime(startDate.Year, startDate.Month, DateTimeEvent.Day,
CustomDateTimeEvent.Times.Hour, CustomDateTimeEvent.Times.Minute, 0)
});
}
return;
}
default:
throw new ArgumentOutOfRangeException();
}
}
}
private static int GetMonthsDifference(DateTime startDate, DateTime endDate)
{
if (startDate > endDate) return 0;
var years = endDate.Year - startDate.Year;
var months = years * 12;
months += endDate.Month - startDate.Month;
if (endDate.Day < startDate.Day) months--;
return months;
}
private struct CustomDateTime
{
public ModeRepeat Mode;
public int DaysInterval;
public int WeeksInterval;
public bool[] DaysOfWeek;
public MyTime Times;
public bool MonthRepeatOnDay, MonthRepeatOnDayOfWeek;
public CustomDateTime(ModeRepeat mode, int daysInterval, int weeksInterval, bool[] daysOfWeek, MyTime times,
bool monthRepeatOnDay, bool monthRepeatOnDayOfWeek)
{
Mode = mode;
Times = times;
DaysOfWeek = new bool[7];
DaysOfWeek.SetArray(daysOfWeek, false);
DaysInterval = daysInterval;
WeeksInterval = weeksInterval;
MonthRepeatOnDay = monthRepeatOnDay;
MonthRepeatOnDayOfWeek = monthRepeatOnDayOfWeek;
}
public bool HasDayOfWeek(DayOfWeek dayOfWeek)
{
return DaysOfWeek != null && DaysOfWeek[(int) dayOfWeek];
}
}
public struct MyTime
{
public int Hour;
public int Minute;
public MyTime(int hour, int minute)
{
Hour = hour;
Minute = minute;
}
}
private class ScreenInterfaceSetup : UserInterfaceSetup
{
[JsonProperty(LangRu ? "Цвет фона экрана" : "Screen background color")]
public IColor BackgroundScreen;
[JsonProperty("Material")] public string Material;
[JsonProperty("Sprite")] public string Sprite;
[JsonProperty(LangRu ? "Кнопка закрытия" : "Button Close")]
public ButtonCloseSetup ButtonClose = new();
public void AddScreenUI(List<CuiElement> container, string parent, string name, string destroy)
{
container.Add(new CuiElement
{
Parent = parent,
Name = name,
DestroyUi = destroy,
Components =
{
new CuiImageComponent
{
Color = BackgroundScreen.Get(),
Sprite = "assets/content/ui/UI.Background.TileTex.psd",
Material = "assets/content/ui/uibackgroundblur-ingamemenu.mat",
ImageType = Image.Type.Tiled
},
FullScreenTransform,
new CuiNeedsCursorComponent(),
new CuiNeedsKeyboardComponent()
}
});
}
}
private class UserInterfaceSetup
{
[JsonProperty(LangRu ? "Главная панель" : "Main panel")]
public ImageSettings MainPanel;
[JsonProperty(LangRu ? "Заголовок" : "Header")]
public PanelHeaderUI HeaderPanel;
[JsonProperty(LangRu ? "Кнопка изменения расписания" : "Schedule change button")]
public ButtonSettings ButtonSetup;
[JsonProperty(LangRu ? "Календарь" : "Calendar")]
public PanelCalendarUI PanelCalendar;
#region Classes
public class PanelHeaderUI
{
[JsonProperty(LangRu ? "Фон" : "Background")]
public ImageSettings Background = new();
[JsonProperty(LangRu ? "Показать заголовок?" : "Show the title?")]
public bool ShowHeader;
[JsonProperty(LangRu ? "Заголовок" : "Title")]
public TextSettings Header = new();
[JsonProperty(LangRu ? "Показать линию" : "Show Line?")]
public bool ShowLine;
[JsonProperty(LangRu ? "Линия" : "Line")]
public ImageSettings Line = new();
}
public class PanelCalendarUI
{
[JsonProperty(LangRu ? "Фон" : "Background")]
public ImageSettings Background = new();
[JsonProperty(LangRu ? "Дни Недели" : "Day Of Week")]
public DayOfWeekPanelUI DaysOfWeekPanel = new();
[JsonProperty(LangRu ? "Таблица дней" : "Table of days")]
public DaysTableUI DaysTable = new();
[JsonProperty(LangRu ? "Расписание" : "Schedule")]
public PanelScheduleUI PanelSchedule = new();
public class DayOfWeekPanelUI
{
[JsonProperty(LangRu ? "Фон" : "Background")]
public ImageSettings Background = new();
[JsonProperty(LangRu ? "Название" : "Title")]
public TextSettings Title = new();
}
public class DaysTableUI
{
[JsonProperty(LangRu ? "Фон" : "Background")]
public ImageSettings Background = new();
[JsonProperty(LangRu ? "Отступы по горизонтали (%)" : "Horizontal margins (%)")]
public float MarginsHorizontal = 10;
[JsonProperty(LangRu ? "Отступы по вертикали (%)" : "Vertical margins (%)")]
public float MarginsVertical = 10;
[JsonProperty(LangRu
? "Фон дня в таблице текущего месяца"
: "Background of the day in the current month table")]
public ButtonSettings BackgroundDayTableInside = new();
[JsonProperty(LangRu
? "Фон дня в таблице за пределами текущего месяца"
: "The background of the day in the table outside the current month")]
public ButtonSettings BackgroundDayTableOutside = new();
}
public class PanelScheduleUI
{
[JsonProperty(LangRu ? "Фон панели месяца" : "Background of the month panel")]
public ImageSettings BackgroundMonth = new();
[JsonProperty(LangRu ? "Название месяца" : "Title of the month")]
public TextSettings TitleMonth = new();
[JsonProperty(LangRu ? "Кнопка предыдущего месяца" : "The button of the previous month")]
public ButtonSettings ButtonPreviousMonth = new();
[JsonProperty(LangRu ? "Кнопка следующего месяца" : "Next Month's button")]
public ButtonSettings ButtonNextMonth = new();
[JsonProperty(LangRu ? "Панель расписания дня" : "The schedule panel of the day")]
public PanelShowDayUI PanelShowDay = new();
[JsonProperty(LangRu ? "Панель аннотации" : "The Annotation panel")]
public ScheduleInfoUI ScheduleInfo = new();
public class PanelShowDayUI
{
[JsonProperty(LangRu ? "Фон" : "Background")]
public ImageSettings Background = new();
[JsonProperty(LangRu ? "Заголовок" : "Header")]
public PanelHeaderUI PanelHeader = new();
// ... [Code preview truncated due to length. Full source in attached file] ...