using System; using System.Collections.Generic; using System.Linq; using Thermo.Active.Model.DatabaseModels; using Thermo.Active.Model.DTOModels; using static CMS_CORE_Library.Models.DataStructures; using static Thermo.Active.Config.ServerConfig; namespace Thermo.Active.Database.Controllers { public class FunctionsAccessController : IDisposable { private DatabaseContext dbCtx; public FunctionsAccessController() { // Initialize database context dbCtx = new DatabaseContext(); } public void Dispose() { // Clear database context dbCtx.Dispose(); } public FunctionAccessModel FindEnabledFunctionByName(string functionName) { return dbCtx .FunctionsAccess .Where(x => x.Name == functionName && x.Enabled == true) // Find by name and enabled functions .FirstOrDefault(); } public List GetFunctionsAccess(int roleLevel) { return dbCtx .FunctionsAccess .Select(f => new DTOFunctionAccessModel() // Convert from database model to data transfer model { Id = f.FunctionAccessId, Name = f.Name, Area = f.Area, Enabled = f.Enabled, CanRead = f.ReadLevelMin <= roleLevel, CanWrite = f.WriteLevelMin <= roleLevel }) .ToList(); } public List FindAll() { return dbCtx .FunctionsAccess .ToList(); } public List FindAllFunctionsAndDisableAll() { return dbCtx .FunctionsAccess .Select(x => new DTORuntimeFunctionalityModel() { Id = x.FunctionAccessId, Area = x.Area, Name = x.Name, Enabled = x.PlcId != -1 ? false : x.Enabled // Only PLC function has to be false }) .ToList(); } public List GetFunctionsMappedWithPlc(List functionalityList) { return FunctionsAccessConfig // Find all function access .Select(f => new DTORuntimeFunctionalityModel() { Id = f.FunctionAccessId, Name = f.Name, Area = f.Area, Enabled = GetIfFunctionalityIsActive(functionalityList, f.PlcId, f.Enabled) // Get new enabled data }) .ToList(); } private bool GetIfFunctionalityIsActive(List functionalityList, int id, bool functionAccessIsEnabled) { // If id is not mapped or function is false by database config return if (id == 0 || !functionAccessIsEnabled) return functionAccessIsEnabled; // Find and Return PLC data FunctionalityModel plcFunc = functionalityList.Where(x => x.Id == id).FirstOrDefault(); if (plcFunc == null) return false; // If not found return plcFunc.IsActive; } } }