Иконка ресурса

FREE WipeSchedule : 2.0.8 2.0.8

Нет прав для скачивания
C#:
// Все права принадлежат дискорд сообществу https://discord.gg/VgNHPpNrz6
// #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.8")]
    public class WipeSchedule : RustPlugin
    {
        #region Fields

        [PluginReference] private Plugin ImageLibrary = null, ServerPanel = null;

        public const bool LangRu = true;

        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(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;

            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
                };
            }
        }

        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
            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()] = "Событие",
                [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]] = "Декабрь"
            };

            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",
                [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]
            };
            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);
        }

        #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);
#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)
            };
        }

        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 < 2) return;

                        for (var i = 0; i < daysInMonth; i++)
                            if ((i + 1) % CustomDateTimeEvent.DaysInterval == 0)
                                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.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();

                        [JsonProperty(LangRu ? "Панель прокрутки событий" : "Event Scroll panel")]
                        public ScrollPanelUI ScrollPanel = new();

                        public class PanelHeaderUI
                        {
                            [JsonProperty(LangRu ? "Фон" : "Background")]
                            public ImageSettings Background = new();

                            [JsonProperty(LangRu ? "Число" : "Title")]
                            public TextSettings Number = new();

                            [JsonProperty(LangRu ? "Месяц" : "Month")]
                            public TextSettings Month = new();

                            [JsonProperty(LangRu ? "День недели" : "Day of the week")]
                            public TextSettings DayOfWeek = new();

                            [JsonProperty(LangRu ? "Показать линию" : "Show Line?")]
                            public bool ShowLine;

                            [JsonProperty(LangRu ? "Линия" : "Line")]
                            public ImageSettings Line = new();
                        }
                    }

                    public class ScheduleInfoUI
                    {
                        [JsonProperty(LangRu ? "Фон" : "Background")]
                        public ImageSettings Background = new();

                        [JsonProperty(LangRu ? "Панель информации" : "Information Panel")]
                        public ImageSettings BackgroundInfo = new();

                        [JsonProperty(LangRu ? "Иконка" : "Icon")]
                        public ImageSettings Icon = new();

                        [JsonProperty(LangRu ? "Текст информации" : "The text of the information")]
                        public TextSettings TextInfo = new();

                        [JsonProperty(LangRu ? "Фон панели аннотации" : "Background of the annotation panel")]
                        public ImageSettings BackgroundAnnotation = new();

                        [JsonProperty(
                            LangRu ? "Размер цветового маркера события" : "The size of the event color marker")]
                        public Vector2 SizeMarkerColor;

                        [JsonProperty(LangRu ? "Аннотация цвета события" : "Event color Annotation")]
                        public TextSettings Annotation = new();
                    }
                }
            }

            public class ScrollPanelUI
            {
                [JsonProperty(LangRu ? "Фон" : "Background")]
                public ImageSettings Background = new();

                [JsonProperty(LangRu ? "Вид прокрутки" : "Scroll view")]
                public ScrollViewUI ScrollView = new();

                [JsonProperty(LangRu ? "Содержимое прокрутки" : "Scroll Content")]
                public ContentScrollUI ContentScroll = new();

                public class ContentScrollUI
                {
                    [JsonProperty(LangRu ? "Отступы" : "Margins")]
                    public MarginsInScrollUI MarginsInScroll;

                    [JsonProperty(LangRu ? "Фон элемента в прокрутке" : "Scrolling element background")]
                    public ImageSettings BackgroundContent = new();

                    [JsonProperty(LangRu ? "Высота элемента в прокрутке" : "The height of the element in the scroll")]
                    public float Height;

                    [JsonProperty(LangRu ? "Позиция иконки в элементе" : "The position of the icon in the element")]
                    public InterfacePosition IconTransform = new();

                    [JsonProperty(LangRu ? "Время события" : "Time of the event")]
                    public TextSettings TimeEvent = new();

                    [JsonProperty(LangRu ? "Название типа события" : "Name of the event type")]
                    public TextSettings TitleEvent = new();

                    [JsonProperty(LangRu ? "Кнопка информации о событии" : "Event Information button")]
                    public ButtonSettings ButtonInfo = new();

                    [JsonProperty(LangRu
                        ? "Цвет затенения расписания при открытии описания"
                        : "The shading color of the schedule when opening the description")]
                    public IColor ColorSchedule = new("#000000", 80);

                    [JsonProperty(LangRu ? "Длина панели описания" : "Description Panel length")]
                    public float PanelDescriptionLength = 250;

                    [JsonProperty(LangRu ? "Высота панели описания" : "Description panel height")]
                    public float PanelDescriptionHeight = 120;

                    [JsonProperty(LangRu ? "Фон заголовка панели описания" : "Description panel title background")]
                    public ImageSettings TitlePanelDescription = new();

                    [JsonProperty(LangRu ? "Название события" : "Event title")]
                    public TextSettings TitleEventDescription = new();

                    [JsonProperty(LangRu
                        ? "Фон панели описания панели описания"
                        : "Description panel background description panel")]
                    public ImageSettings DescriptionPanelBackground = new();

                    [JsonProperty(LangRu ? "Описание события" : "Description of the event")]
                    public TextSettings Description = new();
                }
            }

            #endregion

            public static ScreenInterfaceSetup GenerateFullScreen()
            {
                return new ScreenInterfaceSetup
                {
                    BackgroundScreen = new IColor("#191919", 90),
                    Sprite = "assets/content/ui/UI.Background.TileTex.psd",
                    Material = "assets/content/ui/uibackgroundblur-ingamemenu.mat",
                    ButtonClose = new ButtonCloseSetup
                    {
                        BackgroundClose = new ImageSetting
// ... [Code preview truncated due to length. Full source in attached file] ...

Автор
15FPS
Скачиваний
0
Просмотры
1
Первый выпуск
Обновление
Оценка
0.00 звёзд 0 оценок
Сверху