using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data.Entity;
using System.Data.Entity.SqlServer;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

using VRH.Common;
using Vrh.XmlProcessing;
using VRH.Log4Pro.MultiLanguageManager;
using Vrh.Web.Common.Lib;

using Vrh.iScheduler.Report;
using Vrh.OneMessage;

namespace Vrh.Web.iScheduler.Report.Areas.iSchedulerReport.Controllers
{
    /// <summary>
    /// Az area alapvető és alapértelmezett controller osztálya.
    /// </summary>
    public class iSchedulerReportController : BaseController
    {
        #region Check action
        /// <summary>
        /// Ütemezendő objektumok létezésének ellenőrzése.
        /// Az ütemező a <paramref name="list"/>-ben felsorolja, mely
        /// objektumokat ellenőrzi.
        /// </summary>
        /// <param name="xml">A Scheduler.Report xml paraméter fájl xmlparser connection string-je.</param>
        /// <param name="groupId">Az ütemezett objektum csoport azonosítója. Ha üres, akkor az xml paraméterfájlban megadott lesz érvényes.</param>
        /// <param name="list">Az ellenőrzendő objektumok listája, vesszővel elválasztva.</param>
        /// <returns></returns>
        public JsonResult Check(string xml, string list, string groupId)
        {
            try
            {
                #region DEBUG
#if DEBUG
                string thisfn = $"{nameof(iSchedulerReportController)}.{nameof(Check)}: ";
                System.Diagnostics.Debug.WriteLine($"{thisfn}xml={xml}, list={list}, groupId={groupId}");
#endif
                #endregion DEBUG
                if (string.IsNullOrWhiteSpace(xml)) { xml = $"config={SRConstants.DEFAULT_CONFIGNAME};"; }
                var xmlc = new XmlConnection(xml);
                using (var srxp = new SchedulerReportXmlParser(xmlc, base.BaseFolder, base.ForcedLanguageCode, null, groupId))
                {
                    using (var dbc = new SchedulerReportDbContext(srxp.ConnectionString))
                    {
                        string groupid = srxp.GroupId;
                        List<SelectListItem> objectlist = dbc.SchedulerReportPackages
                                                             .Where(x => (groupid == SRConstants.Groups.All || x.GroupId == groupid))
                                                             .Select(s => new SelectListItem() { Value = s.Name, Text = s.Description })
                                                             .ToList();

                        var resultlist = new List<CheckListJSON>();
                        if (!string.IsNullOrEmpty(list))
                        {
                            string[] idlist = list.Split(',');
                            foreach (string id in idlist)
                            {
                                SelectListItem obj = objectlist.FirstOrDefault(x => x.Value == id);
                                resultlist.Add(new CheckListJSON() { Value = id, Text = obj == null ? "" : obj.Text, Checked = obj != null });
                            }
                        }
                        return Json(resultlist, JsonRequestBehavior.AllowGet);
                    }
                }
            }
            catch (Exception ex)
            {
                var result = new List<CheckListJSON>();
                int i = 0;
                foreach (var item in WebCommon.ErrorListBuilder(ex))
                {
                    result.Add(new CheckListJSON { Value = (i++).ToString(), Text = item });
                }
                return Json(result, JsonRequestBehavior.AllowGet);
            }
        }
        #endregion Check action

        #region DeletePackage action
        /// <summary>
        /// Riport csomag törlése akció.
        /// </summary>
        /// <param name="id"></param>
        /// <param name="connectionString"></param>
        /// <param name="deleteRoleUrl"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult DeletePackage(string id, string connectionString, string deleteRoleUrl)
        {
            try
            {
                #region DEBUG
#if DEBUG
                string thisfn = $"{nameof(iSchedulerReportController)}.{nameof(DeletePackage)}: ";
                System.Diagnostics.Debug.WriteLine($"{thisfn}id={id}, connectionString={connectionString}, deleteRoleUrl={deleteRoleUrl}");
#endif
                #endregion DEBUG

                #region Paraméterek ellenőrzése
                if (string.IsNullOrEmpty(id))
                {
                    base.ThrEx(typeof(SRWordCodes.iSchedulerReport.Editor.Messages.IdIsMissingOrEmpty));
                }
                if (!int.TryParse(id, out int packageId))
                {
                    base.ThrEx(typeof(SRWordCodes.iSchedulerReport.Editor.Messages.IdIsNotAnInteger), id);
                }
                if (string.IsNullOrEmpty(deleteRoleUrl))
                {
                    base.ThrEx(typeof(SRWordCodes.iSchedulerReport.Editor.Messages.DeleteRoleUrlIsMissingOrEmpty));
                }
                #endregion Paraméterek ellenőrzése

                using (var dbc = new SchedulerReportDbContext(connectionString))
                {
                    var package = dbc.SchedulerReportPackages.FirstOrDefault(pack => pack.Id == packageId);
                    if (package == null)
                    {
                        ThrEx(typeof(SRWordCodes.iSchedulerReport.Editor.Messages.PackageIsNotFound), id);
                    }

                    #region Szerep törlése

                    #region Web request módszer (obsolete)
                    //var vars = new ScheduleReportVariables
                    //{
                    //    [ScheduleReportVariables.ROLENAME] = package.RoleName
                    //};
                    //string url = vars.Substitution(deleteRoleUrl);
                    //System.Diagnostics.Debug.WriteLine($"{thisfn}deleteRoleUrl={url}");
                    //using (CookieWebClient cwc = new CookieWebClient(this.Request))
                    //{
                    //    var nvc = new NameValueCollection();
                    //    string resp;
                    //    string mess = string.Format(base.Mlmgt(typeof(SRWordCodes.iSchedulerReport.Editor.Messages.DeleteRoleFailed)), url);
                    //    try
                    //    {
                    //        resp = Encoding.UTF8.GetString(cwc.UploadValues(url, nvc));
                    //    }
                    //    catch (Exception ex)
                    //    {
                    //        throw new ApplicationException(mess, cwc.LastException ?? ex);
                    //    }
                    //    System.Diagnostics.Debug.WriteLine($"{thisfn}resp={(resp.Length > 200 ? resp.Substring(0, 200) : resp)}");
                    //    ReturnInfoJSON ri = JsonConvert.DeserializeObject<ReturnInfoJSON>(resp);
                    //    if (ri.ReturnValue != 0) throw new ApplicationException($"{mess}<br />{ri.ReturnMessage}");
                    //}
                    #endregion Web request módszer (obsolete)

                    var roleService = new Vrh.Membership.RoleService();
                    roleService.Delete(package.RoleName);

                    #endregion Szerep törlése

                    dbc.SchedulerReportPackages.Remove(package);
                    dbc.SaveChanges();
                }
                return Json(new ReturnInfoJSON(), JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new ReturnInfoJSON
                {
                    ReturnValue = -1,
                    ReturnMessage = string.Join(WebCommon.HTML_NEWLINE, WebCommon.ErrorListBuilder(ex))
                }, JsonRequestBehavior.AllowGet);
            }
        }
        #endregion DeletePackage action

        #region Editor action

        #region Editor GET
        /// <summary>
        /// Riportcsomag szerkesztő felület belépő akciója.
        /// </summary>
        /// <param name="xml">
        /// A Scheduler.Report xml paraméter fájl XmlParser kapcsolati sztringje.
        /// </param>
        /// <param name="groupId"> 
        /// Módosításnál nem lehet "*", új rekordnál a "*" jelentése az, 
        /// hogy meg kell adnia egy csoportazonosítót a felületen.
        /// </param>
        /// <param name="objectId">
        /// Tulajdonképpen a csomag neve. Ha üres vagy null, akkor új riportcsomag készül.
        /// </param>
        /// <param name="bootboxid">
        /// Ha ablakban nyitották meg az editor-t, akkor a dialogus ablak HTML elemben (id-ban) szereplő érték.
        /// </param>
        /// <param name="sourceOfCalling">
        /// Annak jelzése, hogy honnan is hívták meg az Editor-t.
        /// </param>
        /// <returns>PartailView: Ha hiba van, akkor Error.cshtml, egyébként a _PackageEditor.cshtml.</returns>
        [HttpGet]
        public ActionResult Editor(string xml, string groupId, string objectId, string bootboxid, string sourceOfCalling)
        {
            try
            {
                #region DEBUG
#if DEBUG
                string thisfn = $"{nameof(iSchedulerReportController)}.{nameof(Editor)} GET: ";
                System.Diagnostics.Debug.WriteLine($"{thisfn}START xml={xml}; groupId={groupId}; objectId={objectId}; sourceOfCalling={sourceOfCalling};");
#endif
                #endregion DEBUG
                var pem = new PackageEditorModel();
                if (string.IsNullOrWhiteSpace(xml)) { xml = $"config={SRConstants.DEFAULT_CONFIGNAME};"; }
                var xmlc = new XmlConnection(xml);
                using (var srxp = new SchedulerReportXmlParser(xmlc, base.BaseFolder, base.ForcedLanguageCode, null, groupId))
                {
                    if (srxp.ErrorList.Any())
                    {
                        SetError(typeof(GeneralWordCodes.MLM.General.Messages.ErrorHeadXML));
                        return PartialView(SRConstants.Views.ERRORLIST, srxp.ErrorList);
                    }

                    #region XML-ből a modelbe (PackageGroupId is értéket kap itt)
                    pem.XmlCs = srxp.XmlParserConnectionString;
                    pem.PackageGroupId = srxp.GroupId == SRConstants.Groups.All ? "" : srxp.GroupId;

                    pem.BootboxId = bootboxid;
                    pem.ConnectionString = srxp.ConnectionString;
                    pem.SourceOfCalling = sourceOfCalling;

                    pem.RoleNameMask = srxp.PackageEditor.RoleNameMask;
                    pem.RolegroupListUrl = srxp.PackageEditor.RolegroupListUrl.GetUrl(true);
                    pem.UserListUrl = srxp.PackageEditor.UserListUrl.GetUrl(true);
                    pem.UsersOfRoleUrl = srxp.PackageEditor.UserListOfRoleUrl.GetUrl(true);
                    pem.CreateRoleUrl = srxp.PackageEditor.CreateRoleUrl.GetUrl(true);
                    pem.DeleteRoleUrl = srxp.PackageEditor.DeleteRoleUrl.GetUrl(true);
                    pem.AssignRoleToRolegroupsUrl = srxp.PackageEditor.AssignRoleToRolegroupsUrl.GetUrl(true);
                    pem.AssignRoleToUsersUrl = srxp.PackageEditor.AssignRoleToUsersUrl.GetUrl(true);

                    pem.ReportListUrl = srxp.PackageEditor.ReportListUrl.GetUrl(true);
                    pem.ReportFormatListUrl = srxp.PackageEditor.ReportFormatListUrl.GetUrl(true);
                    pem.TestExecuteOperation = srxp.PackageEditor.TestExecuteOperation;

                    #endregion XML-ből a modelbe
                }

                if (!string.IsNullOrWhiteSpace(objectId))   //ha van értéke a packageName-nek => módosítás
                {
                    using (var db = new SchedulerReportDbContext(pem.ConnectionString))
                    {
                        if (string.IsNullOrWhiteSpace(pem.PackageGroupId))
                        {
                            ThrEx(typeof(SRWordCodes.iSchedulerReport.Editor.Messages.PackageGroupEmpty));
                        }

                        SchedulerReportPackage srp = db.SchedulerReportPackages.FirstOrDefault(x => x.GroupId == pem.PackageGroupId
                                                                                                 && x.Name == objectId);
                        if (srp == null)
                        {
                            ThrEx(typeof(SRWordCodes.iSchedulerReport.Editor.Messages.PackageIsNotFoundByNameGroup), objectId, groupId);
                        }

                        pem.PackageId = srp.Id;
                        pem.PackageName = srp.Name;
                        pem.PackageDescription = srp.Description;
                        pem.PackageRoleName = srp.RoleName;
                        pem.PackageIsActive = srp.Active;

                        pem.SelectedReports = new List<string>();
                        pem.SelectedFormats = new List<string>();
                        foreach (SchedulerReportPackageItem pi in srp.SchedulerReportPackageItems)
                        {
                            pem.SelectedReports.Add(string.Concat(pi.ReportId, "/", pi.LCID, "/", pi.PresetId));
                            pem.SelectedFormats.Add(pi.ExportType);
                        }
                    }
                }
                return PartialView(SRConstants.Views.EDITOR, pem);
            }
            catch (Exception ex)
            {
                SetError(typeof(SRWordCodes.iSchedulerReport.Editor.Titles.EditorInitializationIsFailed));
                return PartialView(SRConstants.Views.ERRORLIST, WebCommon.ErrorListBuilder(ex));
            }
        }
        #endregion Editor GET

        #region Editor POST
        /// <summary>
        /// Riport csomag szerkesztése felület POST akciója.
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Editor(PackageEditorModel model)
        {
            #region DEBUG
#if DEBUG
            string thisfn = $"{nameof(iSchedulerReportController)}.{nameof(Editor)} POST: ";
            System.Diagnostics.Debug.WriteLine($"{thisfn}PING");
#endif
            #endregion DEBUG

            if (ModelState.IsValid)
            {
                try
                {
                    using (var db = new SchedulerReportDbContext(model.ConnectionString))
                    {
                        #region Adatok ellenőrzése és mentése 

                        SchedulerReportPackage srp;

                        #region Ellenőrzések
                        if (model.PackageId == 0)
                        {   //felvitel
                            if (db.SchedulerReportPackages.Any(x => x.GroupId == model.PackageGroupId && x.Name == model.PackageName))
                            {
                                ThrEx(typeof(SRWordCodes.iSchedulerReport.Editor.Messages.SamePackageNameInsideGroup), model.PackageGroupId, model.PackageName);
                            }
                            srp = new SchedulerReportPackage();
                        }
                        else
                        {   //módosítás
                            srp = db.SchedulerReportPackages.Find(model.PackageId);
                            if (srp == null) ThrEx(typeof(SRWordCodes.iSchedulerReport.Editor.Messages.PackageIsNotFound), model.PackageId);

                            List<SchedulerReportPackageItem> items = srp.SchedulerReportPackageItems.ToList();
                            foreach (SchedulerReportPackageItem srpi in items)
                            {
                                db.SchedulerReportPackageItems.Remove(srpi);
                            }
                            //db.SaveChanges();
                        }
                        if (string.IsNullOrWhiteSpace(model.PackageGroupId))
                        {
                            ThrEx(typeof(SRWordCodes.iSchedulerReport.Editor.Messages.PackageGroupEmpty));
                        }
                        if (model.PackageGroupId.Length < 3 || model.PackageGroupId.Length > 100)
                        {
                            ThrEx(typeof(SRWordCodes.iSchedulerReport.Editor.Messages.PackageGroupLength));
                        }
                        if (!Regex.IsMatch(model.PackageGroupId, @"[a-zA-Z0-9_]\w*"))
                        {
                            ThrEx(typeof(SRWordCodes.iSchedulerReport.Editor.Messages.PackageGroupInvalid));
                        }
                        #endregion Ellenőrzések

                        srp.GroupId = model.PackageGroupId;
                        srp.Name = model.PackageName;
                        srp.Description = model.PackageDescription;
                        srp.RoleName = model.PackageRoleName;
                        srp.Active = model.PackageIsActive;

                        if (model.SelectedReports.Any())
                        {
                            srp.SchedulerReportPackageItems = new HashSet<SchedulerReportPackageItem>();
                            int ix = 0;
                            foreach (string slctd in model.SelectedReports)
                            {
                                string[] ids = slctd.Split('/');
                                if (ids.Count() != 3) ThrEx(typeof(SRWordCodes.iSchedulerReport.Editor.Messages.ReportIdIsWrong), slctd);

                                var srpi = new SchedulerReportPackageItem()
                                {
                                    ReportId = ids[0],
                                    LCID = ids[1],
                                    PresetId = ids[2],
                                    ExportType = model.SelectedFormats[ix],
                                };
                                srp.SchedulerReportPackageItems.Add(srpi);
                                ix++;
                            }
                        }
                        if (model.PackageId == 0) db.SchedulerReportPackages.Add(srp);
                        db.SaveChanges();
#if DEBUG
                        System.Diagnostics.Debug.WriteLine($"{thisfn}Sikeres mentés.");
#endif

                        #endregion Adatok ellenőrzése és mentése 

                        string dialogtitle = base.Mlmgt(typeof(SRWordCodes.iSchedulerReport.Editor.Messages.Acknowledgment));
                        string labelaction = base.Mlmgt(typeof(SRWordCodes.iSchedulerReport.Editor.Messages.AcknowledgmentActionLabel));
                        string labelmessage = base.Mlmgt(typeof(SRWordCodes.iSchedulerReport.Editor.Messages.AcknowledgmentMessageLabel));
                        bool isLargeDialog = false;
                        string onerow = "<tr><td>{0}</td><td>{1}</td></tr>";
                        string acknowledgment = string.Concat(
                            "<table>",
                            string.Format(onerow, labelaction, labelmessage));

                        string head;
                        try
                        {
                            var roleService = new Vrh.Membership.RoleService();
                            string operationOK = base.Mlmgt(typeof(SRWordCodes.iSchedulerReport.Editor.Messages.OperationSuccessful));
                            string operationNOK = base.Mlmgt(typeof(SRWordCodes.iSchedulerReport.Editor.Messages.OperationUnSuccessful));
                            var edvars = new ScheduleReportVariables
                            {
                                [ScheduleReportVariables.ROLENAME] = model.PackageRoleName
                            };

                            #region DEBUG TEST 
                            //System.Diagnostics.Debug.WriteLine("\nHttpWebRequest TEST");
                            //UrlElement testue = new UrlElement() { Area = "iSchedulerReport", Controller = "iSchedulerReport", Action = "ListOperations" };
                            //string testurl = testue.GetUrl(this.Request);
                            //HttpWebRequest hreq = null;
                            //HttpWebResponse hresp = null;
                            //try
                            //{
                            //    hreq = (HttpWebRequest)WebRequest.Create(testurl);  //Request léterhozása
                            //    hreq.CookieContainer = new CookieContainer();       //Cookie container inicializálása
                            //    foreach (string cookieName in this.Request.Cookies) //a helyi request-ből a cookie-k átmásolása
                            //    {
                            //        HttpCookie cookie = this.Request.Cookies[cookieName];
                            //        System.Net.Cookie ncookie = new Cookie()
                            //        {
                            //            Expires = cookie.Expires,
                            //            Domain = this.Request.Url.Host,
                            //            HttpOnly = cookie.HttpOnly,
                            //            Name = cookie.Name,
                            //            Path = cookie.Path,
                            //            Secure = cookie.Secure,
                            //            Value = cookie.Value,
                            //        };
                            //        hreq.CookieContainer.Add(this.Request.Url, ncookie);
                            //    }
                            //    hresp = (HttpWebResponse)hreq.GetResponse();
                            //    System.Diagnostics.Debug.WriteLine("hresp: Content length is {0}", hresp.ContentLength);
                            //    System.Diagnostics.Debug.WriteLine("hresp: Content type is {0}", hresp.ContentType);
                            //    System.Diagnostics.Debug.WriteLine("hresp: Result:");

                            //    using (Stream hrespStream = hresp.GetResponseStream())
                            //    {
                            //        using (StreamReader sr = new StreamReader(hrespStream, Encoding.UTF8))
                            //        {
                            //            List<SelectListJSON> ops = JsonConvert.DeserializeObject<List<SelectListJSON>>(sr.ReadToEnd());
                            //            foreach (SelectListJSON slj in ops)
                            //            {
                            //                System.Diagnostics.Debug.WriteLine($"Value={slj.Value}, Text={slj.Text}");
                            //            }
                            //            sr.Close();
                            //        }
                            //        hrespStream.Close();
                            //    }
                            //}
                            //catch (Exception ex)
                            //{
                            //    System.Diagnostics.Debug.WriteLine($"hresp ERROR: message={ErrorMessageBuilder(ex)}");
                            //}
                            //finally
                            //{
                            //    if (hresp != null) hresp.Close();
                            //    hresp = null;
                            //    hreq = null; 
                            //}  
                            #endregion DEBUG TEST     

                            #region Call UserAdministration actions

                            #region Szerep létrehozása
                            #region Web request módszer (obsolete)
                            //head = base.Mlmgt(typeof(WordCodes.iSchedulerReport.Editor.Messages.CreateRole));
                            //string createurl = edvars.Substitution(model.CreateRoleUrl);
                            //System.Diagnostics.Debug.WriteLine($"{thisfn} CreateNewRole timeout={cwc.Timeout}s, createurl={createurl}");
                            //try
                            //{
                            //    string resp = Encoding.UTF8.GetString(cwc.UploadValues(createurl, nvc)); //post, mert adatot változtat
                            //    ReturnInfoJSON ri = JsonConvert.DeserializeObject<ReturnInfoJSON>(resp);
                            //    acknowledgment += String.Format(onerow, head, ri.ReturnMessage);
                            //    if (ri.ReturnValue == 0) dialogwidth = "500";
                            //}
                            //catch (Exception ex)
                            //{
                            //    string message = String.Concat(ErrorMessageBuilder(cwc.LastException == null ? ex : cwc.LastException), createurl);
                            //    acknowledgment += String.Format(onerow, head, message);
                            //    dialogwidth = "1000";
                            //}
                            #endregion Web request módszer

                            head = base.Mlmgt(typeof(SRWordCodes.iSchedulerReport.Editor.Messages.CreateRole));
                            try
                            {
                                roleService.Create(edvars[ScheduleReportVariables.ROLENAME]);
                                acknowledgment += string.Format(onerow, head, operationOK);
                            }
                            catch (Exception ex)
                            {
                                acknowledgment += string.Format(onerow, head, string.Concat(
                                    operationNOK, WebCommon.HTML_NEWLINE,
                                    string.Join(WebCommon.HTML_NEWLINE, WebCommon.ErrorListBuilder(ex))
                                    ));
                                //isLargeDialog = true;
                            }
                            #endregion Szerep létrehozása

                            #region Szerepkör és felhasználó hozzárendelés
                            if (model.PackageRolegroups == "-1") model.PackageRolegroups = null;
                            if (model.PackageUsers == "-1") model.PackageUsers = null;
                            if (!string.IsNullOrWhiteSpace(model.PackageRolegroups) || !string.IsNullOrWhiteSpace(model.PackageUsers))
                            {   //ha adott meg szerepköröket vagy felhasználókat, akkor el kell végezni az összerendelést
                                if (!string.IsNullOrWhiteSpace(model.PackageRolegroups))
                                {
                                    #region Web request módszer
                                    //head = base.Mlmgt(typeof(WordCodes.iSchedulerReport.Editor.Messages.AssignToRolegroups));
                                    //edvars.ROLEGROUPLIST.Value = model.PackageRolegroups.Trim().Substring(0, model.PackageRolegroups.Length - 1);
                                    //string url = edvars.Substitution(model.AssignRoleToRolegroupsUrl);
                                    //System.Diagnostics.Debug.WriteLine($"{thisfn} rolegroup hozzárendelés: url={url}");
                                    //try
                                    //{
                                    //    string resp = Encoding.UTF8.GetString(cwc.UploadValues(url, nvc)); //post, mert adatot változtat
                                    //    System.Diagnostics.Debug.WriteLine($"{thisfn} rolegroup hozzárendelés: resp={(resp.Length > 200 ? resp.Substring(0, 200) : resp)}");
                                    //    ReturnInfoJSON ri = JsonConvert.DeserializeObject<ReturnInfoJSON>(resp);
                                    //    acknowledgment += String.Format(onerow, head, ri.ReturnMessage);
                                    //    if (ri.ReturnValue == 0) dialogwidth = "500";
                                    //}
                                    //catch (Exception ex)
                                    //{
                                    //    string message = String.Concat(ErrorMessageBuilder(cwc.LastException == null ? ex : cwc.LastException), url);
                                    //    acknowledgment += String.Format(onerow, head, message);
                                    //    dialogwidth = "1000";
                                    //}
                                    #endregion Web request módszer

                                    #region DEBUG
#if DEBUG
                                    System.Diagnostics.Debug.WriteLine($"{thisfn} rolegroup hozzárendelés: PackageRolegroups='{model.PackageRolegroups}'");
#endif
                                    #endregion DEBUG
                                    head = base.Mlmgt(typeof(SRWordCodes.iSchedulerReport.Editor.Messages.AssignToRolegroups));
                                    try
                                    {
                                        string roleGroups = model.PackageRolegroups.Trim().Substring(0, model.PackageRolegroups.Length - 1);
                                        roleService.Assignment(Vrh.Membership.AssignmentMode.RolesToRoleGroups, model.PackageRoleName, roleGroups);
                                        acknowledgment += string.Format(onerow, head, operationOK);
                                    }
                                    catch (Exception ex)
                                    {
                                        acknowledgment += string.Format(onerow, head, string.Concat(
                                            operationNOK, WebCommon.HTML_NEWLINE,
                                            string.Join(WebCommon.HTML_NEWLINE, WebCommon.ErrorListBuilder(ex))
                                            ));
                                        isLargeDialog = true;
                                    }
                                }
                                if (!string.IsNullOrWhiteSpace(model.PackageUsers))
                                {
                                    #region Web request módszer
                                    //head = base.Mlmgt(typeof(WordCodes.iSchedulerReport.Editor.Messages.AssignToUsers));
                                    //edvars.USERLIST.Value = model.PackageUsers.Trim().Substring(0, model.PackageUsers.Length - 1);
                                    //string url = edvars.Substitution(model.AssignRoleToUsersUrl);
                                    //System.Diagnostics.Debug.WriteLine($"{thisfn} user hozzárendelés: url={url}");
                                    //try
                                    //{
                                    //    string resp = Encoding.UTF8.GetString(cwc.UploadValues(url, nvc)); //post, mert adatot változtat
                                    //    System.Diagnostics.Debug.WriteLine($"{thisfn} user hozzárendelés: resp={(resp.Length > 200 ? resp.Substring(0, 200) : resp)}");
                                    //    ReturnInfoJSON ri = JsonConvert.DeserializeObject<ReturnInfoJSON>(resp);
                                    //    acknowledgment += String.Format(onerow, head, ri.ReturnMessage);
                                    //    if (ri.ReturnValue == 0) dialogwidth = "500";
                                    //}
                                    //catch (Exception ex)
                                    //{
                                    //    string message = String.Concat(ErrorMessageBuilder(cwc.LastException == null ? ex : cwc.LastException), url);
                                    //    acknowledgment += String.Format(onerow, head, message);
                                    //    dialogwidth = "1000";
                                    //}
                                    #endregion Web request módszer

                                    #region DEBUG
#if DEBUG
                                    System.Diagnostics.Debug.WriteLine($"{thisfn} user hozzárendelés PackageUsers='{model.PackageUsers}'");
#endif
                                    #endregion DEBUG
                                    head = base.Mlmgt(typeof(SRWordCodes.iSchedulerReport.Editor.Messages.AssignToUsers));
                                    try
                                    {
                                        string userList = model.PackageUsers.Trim().Substring(0, model.PackageUsers.Length - 1);
                                        roleService.Assignment(Vrh.Membership.AssignmentMode.RolesToUsers, model.PackageRoleName, userList);
                                        acknowledgment += string.Format(onerow, head, operationOK);
                                    }
                                    catch (Exception ex)
                                    {
                                        acknowledgment += string.Format(onerow, head, string.Concat(
                                            operationNOK, WebCommon.HTML_NEWLINE,
                                            string.Join(WebCommon.HTML_NEWLINE, WebCommon.ErrorListBuilder(ex))
                                            ));
                                        isLargeDialog = true;
                                    }
                                }
                            }
                            #endregion Szerepkör és felhasználó hozzárendelés

                            #endregion Call UserAdministration actions

                            #region Teszt futtatás
                            if (model.IsTestExecute)
                            {
                                #region Web request módszer (most comment)
                                //if (model.ResponseTimeout > 0) cwc.Timeout = model.ResponseTimeout * 1000;
                                //head = base.Mlmgt(typeof(WordCodes.iSchedulerReport.Editor.Messages.TextExecute));
                                //edvars.THISXMLFILE.Value = model.XmlFile;
                                //edvars.GROUPID.Value = model.PackageGroupId;
                                //edvars.OBJECTID.Value = model.PackageName;
                                //edvars.NOW.Value = DateTime.Now.ToString("yyyyMMddHHmmss");
                                //string url = edvars.Substitution(model.TestExecuteUrl);
                                //System.Diagnostics.Debug.WriteLine($"{thisfn} teszt futtatás: url={url}");
                                //try
                                //{
                                //    string resp = Encoding.UTF8.GetString(cwc.UploadValues(url, nvc)); //post, mert adatot változtat
                                //    System.Diagnostics.Debug.WriteLine($"{thisfn} teszt futtatás: resp={(resp.Length > 200 ? resp.Substring(0, 200) : resp)}");
                                //    ReturnInfoJSON ri = JsonConvert.DeserializeObject<ReturnInfoJSON>(resp);
                                //    acknowledgment += String.Format(onerow, head, ri.ReturnMessage);
                                //    if (ri.ReturnValue == 0) dialogwidth = "500";
                                //}
                                //catch (Exception ex)
                                //{
                                //    string message = String.Concat(ErrorMessageBuilder(cwc.LastException == null ? ex : cwc.LastException), url);
                                //    acknowledgment += String.Format(onerow, head, message);
                                //    dialogwidth = "1000";
                                //}
                                #endregion Web request módszer (most comment)

                                head = base.Mlmgt(typeof(SRWordCodes.iSchedulerReport.Editor.Messages.TextExecute));
                                try
                                {
                                    SchedulerPlugin schedulerPlugin = new SchedulerPlugin();
                                    ReturnInfoJSON ri = schedulerPlugin.ExecuteScheduledTask(
                                        model.XmlCs,
                                        base.ForcedLanguageCode,
                                        model.PackageName,
                                        model.TestExecuteOperation, // SRConstants.Operations.EXECUTE_KEY
                                        DateTime.Now.ToString("yyyyMMddHHmmss"),
                                        model.PackageGroupId
                                    );
                                    acknowledgment += string.Format(onerow, head, ri.ReturnMessage);
                                    isLargeDialog = ri.ReturnValue != 0;
                                }
                                catch (Exception ex)
                                {
                                    string message = string.Join(WebCommon.HTML_NEWLINE, WebCommon.ErrorListBuilder(ex));
                                    acknowledgment += string.Format(onerow, head, message);
                                    isLargeDialog = true;
                                }
                            }
                            #endregion Teszt futtatás
                        }
                        catch (Exception ex)
                        {
                            acknowledgment += string.Format(onerow, "", string.Join(WebCommon.HTML_NEWLINE, WebCommon.ErrorListBuilder(ex)));
                            isLargeDialog = true;
                        }

                        acknowledgment = string.Concat(
                            HttpUtility.JavaScriptStringEncode(acknowledgment.Replace("\r\n", WebCommon.HTML_NEWLINE).Replace("\r", WebCommon.HTML_NEWLINE).Replace("\n", WebCommon.HTML_NEWLINE)),
                            "</table>"
                            );
                        string script = $"showEditorReturnInfo('{acknowledgment}','{dialogtitle}'," + (isLargeDialog ? "true" : "false") + ");";

                        #region DEBUG
#if DEBUG
                        System.Diagnostics.Debug.WriteLine($"{thisfn}END script={script}");
#endif
                        #endregion DEBUG

                        return JavaScript(script);
                    }//using (iSchedulerDB db = new iSchedulerDB(model.ConnectionString))
                }
                catch (Exception ex)
                {
                    AddModelError(ex);
                }
            }
            TempData[MODELSTATE] = ModelState;
            return PartialView(SRConstants.Views.EDITOR, model);
        }
        #endregion Editor POST

        #endregion Editor action

        #region Execute action
        private bool m_IsOwnError = false;
        /// <summary>
        /// Megadott reportcsomagon a művelet végrehajtása.
        /// </summary>
        /// <param name="xml">A Scheduler.Report xml paraméter fájl xmlparser connection string-je.</param>
        /// <param name="GroupId">Kötelező paraméter, nem lehet "*"</param>
        /// <param name="ObjectId"></param>
        /// <param name="OperationId"></param>
        /// <param name="TimeStamp"></param>
        /// <returns></returns>
        public JsonResult Execute(string xml, string GroupId, string ObjectId, string OperationId, string TimeStamp, bool formatreturnmessage=false)
        {
            m_IsOwnError = false; 
            ReturnInfoJSON rijson = new ReturnInfoJSON();

            string header = base.Mlmgt(typeof(SRWordCodes.iSchedulerReport.Execute.ActionIsCompleted));
            string headerformatted = $"{header}<br/><table>";
            string firstrowtemplate = $"<tr><th>{base.Mlmgt(typeof(SRWordCodes.iSchedulerReport.Execute.ColName))}</th><th>{base.Mlmgt(typeof(SRWordCodes.iSchedulerReport.Execute.ColVal))}</th></tr>";
            string onerowtemplate = "<tr><td>{0}</td><td>{1}</td></tr>";
            string footer = "</table>";
            string executionmessage = "";
            try
            {
                CheckIfParameterIsEmpty(GroupId, "GroupId");
                CheckIfParameterIsEmpty(ObjectId, "ObjectId");
                TimeStamp = TimeStamp ?? (DateTime.Now.ToString("yyyyMMddHHmmss")); CheckIfParameterIsEmpty(TimeStamp, "TimeStamp");
                OperationId = OperationId ?? (SRConstants.Operations.EXECUTE_KEY); CheckIfParameterIsEmpty(OperationId, "OperationId");

                if (String.IsNullOrEmpty(xml)) xml = "???";
                executionmessage = (new SchedulerPlugin()).ExecuteScheduledTask(xml, base.ForcedLanguageCode, ObjectId, OperationId, TimeStamp, GroupId).ReturnMessage;
                rijson.ReturnValue = 0;
            }
            catch (Exception ex)
            {
                rijson.ReturnValue = -1;
                executionmessage = string.Join(WebCommon.HTML_NEWLINE, WebCommon.ErrorListBuilder(ex));
            }
            rijson.ReturnMessage = String.Join(
                    headerformatted, firstrowtemplate,
                    string.Format(onerowtemplate, "xml", xml),
                    string.Format(onerowtemplate, "GroupId", GroupId),
                    string.Format(onerowtemplate, "ObjectId", ObjectId),
                    string.Format(onerowtemplate, "TimeStamp", TimeStamp),
                    string.Format(onerowtemplate, "Message", executionmessage),
                    footer
                    );
            if (!formatreturnmessage)
            {
                rijson.ReturnMessage= rijson.ReturnMessage
                .Replace("<br/>", ";").Replace("<br />", ";").Replace("<table>", "").Replace("</table>", "").Replace("<tr>", "")
                .Replace("</td><td>", "=").Replace("</th><th>", "=")
                .Replace("</td></tr>", ",").Replace("</th></tr>", ",")
                .Replace("<td>", "").Replace("<th>", "").Replace("<tr>", "");
            }
            return Json(rijson, JsonRequestBehavior.AllowGet);
        }
        #endregion Execute action

        #region SendSMTPMessage action
        /// <summary>
        /// Vrh.OneMessage SMTP küldés belépési pontja.
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SendSMTPMessage(string[][] paramlist = null)
        {
            var rij = new ReturnInfoJSON();
            try
            {
                base.ParameterSeparating(typeof(Constants.UParam));
                base.ParameterSeparating(paramlist, typeof(Constants.UParam));

                if (String.IsNullOrWhiteSpace(base.RequestedParameters[Constants.UParam.LCID])) { base.RequestedParameters[Constants.UParam.LCID] = base.ForcedLanguageCode; }
                else { base.ForcedLanguageCode = base.RequestedParameters[Constants.UParam.LCID]; }

                if (string.IsNullOrWhiteSpace(base.RequestedParameters[Constants.UParam.MSGID])) { throw new Exception($"Az '{Constants.UParam.MSGID}' URL paraméter hiányzik!"); }

                var omp = new OneMessageParameters(base.RequestedParameters.ToList(), base.OtherParameters.ToList(), Server.MapPath(WebCommon.SIGN_RELATIVE));

                var om = new Vrh.OneMessage.OneMessage(omp);

                if (om.ErrorList.Count == 0)
                {   //ha nem volt hiba a feldolgozás közben, következhet a küldés
                    om.SendMessage();
                    rij.ReturnValue = 0;
                    rij.ReturnMessage = "Az üzenet elküldése sikeresen megtörtént.";
                }
                else
                {
                    rij.ReturnValue = -1;
                    rij.ReturnMessage = string.Join(WebCommon.HTML_NEWLINE, om.ErrorList);
                }
            }
            catch (Exception ex)
            {
                rij.ReturnValue = -1;
                rij.ReturnMessage = string.Join(WebCommon.HTML_NEWLINE, WebCommon.ErrorListBuilder(ex));
            }
            return Json(rij, JsonRequestBehavior.AllowGet);
        }
        #endregion SendSMTPMessage action


        #region Manager action
        /// <summary>
        /// A riport csomagok kilistázását eredményező nézet előkészítése.
        /// </summary>
        /// <param name="xml">XmlParser kapcsolati sztring.</param>
        /// <param name="groupId">
        /// Csoportazonosító, amelyre szűrni kell. 
        /// Ha üres, akkor az XML fájlban lévő csoportazonosítóra szűr.
        /// </param>
        /// <returns>Hiba esetén "ErrorList", egyébként a "Manager" nézet.</returns>
        [HttpGet]
        public ActionResult Manager(string xml, string groupId)
        {
            try
            {
                #region DEBUG
#if DEBUG
                string thisfn = $"{nameof(iSchedulerReportController)}.{nameof(Manager)}: ";
                System.Diagnostics.Debug.WriteLine($"{thisfn}START xml={xml}; groupId={groupId}");
#endif
                #endregion DEBUG
                if (string.IsNullOrWhiteSpace(xml)) { xml = $"config={SRConstants.DEFAULT_CONFIGNAME};"; }
                var xmlc = new XmlConnection(xml);
                using (var srxp = new SchedulerReportXmlParser(xmlc, base.BaseFolder, base.ForcedLanguageCode, null, groupId))
                {
                    if (srxp.ErrorList.Any())
                    {
                        SetError(typeof(GeneralWordCodes.MLM.General.Messages.ErrorHeadXML));
                        return View(SRConstants.Views.ERRORLIST, srxp.ErrorList);
                    }
                    else
                    {
                        var model = new ManagerViewModel
                        {
                            PackageGroupId = srxp.GroupId,
                            XmlCs = srxp.XmlParserConnectionString,
                            ConnectionString = srxp.ConnectionString,
                            DeleteRoleUrl = srxp.PackageEditor.DeleteRoleUrl.GetUrl(true),
                        };
                        return View(SRConstants.Views.MANAGER, model);
                    }
                }
            }
            catch (Exception ex)
            {
                SetError(typeof(GeneralWordCodes.MLM.General.Messages.ErrorHeadAction), nameof(Manager));
                return View(SRConstants.Views.ERRORLIST, WebCommon.ErrorListBuilder(ex));
            }
        }
        #endregion Manager action

        #region List action
        /// <summary>
        /// Riport csomagok listáját visszaadó akció.
        /// </summary>
        /// <param name="xml">XmlParser kapcsolati sztring.</param>
        /// <param name="groupId">Csoportazonosító, amelyre szűrni kell. Ha üres, akkor az XML fájlban lévő csoportazonosítóra szűr.</param>
        /// <param name="activeOnly">Ha csak az aktívnak jelölt csomagok kellenek.</param>
        /// <param name="query">Az "autocomplete" szűrés kereső karaktere(i).</param>
        /// <returns></returns>
        public JsonResult List(string xml, string groupId, string activeOnly, string query)
        {
            try
            {
                #region DEBUG
#if DEBUG
                string thisfn = $"{nameof(iSchedulerReportController)}.{nameof(List)}: ";
                System.Diagnostics.Debug.WriteLine($"{thisfn}query={query}, GroupId={groupId}, xml={xml}, ActiveOnly={activeOnly}");
#endif
                #endregion DEBUG
                if (string.IsNullOrWhiteSpace(xml)) { xml = $"config={SRConstants.DEFAULT_CONFIGNAME};"; }
                var xmlc = new XmlConnection(xml);
                using (var srxp = new SchedulerReportXmlParser(xmlc, base.BaseFolder, base.ForcedLanguageCode, null, groupId))
                {
                    bool allPackage = true;
                    if (!string.IsNullOrWhiteSpace(activeOnly))
                    {
                        if (bool.TryParse(activeOnly, out bool ap))
                        {
                            allPackage = !ap;
                        }
                    }
                    var resultlist = new List<SelectListJSON>();
                    using (var dbc = new SchedulerReportDbContext(srxp.ConnectionString))
                    {
                        string groupid = srxp.GroupId;
                        query = query ?? "";
                        resultlist = dbc.SchedulerReportPackages
                                        .Where(x => (groupid == SRConstants.Groups.All || x.GroupId == groupid)
                                                 && (SqlFunctions.PatIndex("%" + query + "%", x.Description + " (" + x.Name + ")") > 0)
                                                 && (allPackage || x.Active)
                                              )
                                        .Select(s => new SelectListJSON() { Value = s.Name, Text = s.Description + " (" + s.Name + ")", Disabled = !s.Active })
                                        .ToList();
                    }
                    return Json(resultlist, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                var result = new List<SelectListJSON>();
                int i = 0;
                foreach (var item in WebCommon.ErrorListBuilder(ex))
                {
                    result.Add(new SelectListJSON { Value = (i++).ToString(), Text = item });
                }
                return Json(result, JsonRequestBehavior.AllowGet);
            }

        }
        #endregion List action

        #region ListOperations action
        /// <summary>
        /// Az riportokon végrehajtható műveleteket visszaadó akció.
        /// </summary>
        /// <param name="query">Az "autocomplete" szűrés kereső karaktere(i).</param>
        /// <returns></returns>
        public JsonResult ListOperations(string query)
        {
            try
            {
                #region DEBUG
#if DEBUG
                string thisfn = $"{nameof(iSchedulerReportController)}.{nameof(ListOperations)}: ";
                System.Diagnostics.Debug.WriteLine($"{thisfn}query={query}");
#endif
                #endregion DEBUG
                var resultlist = new List<SelectListJSON>();
                if (string.IsNullOrWhiteSpace(query))
                {
                    foreach (KeyValuePair<string, string> kvp in SRGlobal.Operations)
                    {
                        resultlist.Add(new SelectListJSON() { Value = kvp.Key, Text = kvp.Value });
                    }
                }
                else
                {
                    query = query.ToLower();
                    foreach (KeyValuePair<string, string> kvp in SRGlobal.Operations)
                    {
                        if (kvp.Value.ToLower().Contains(query))
                        {
                            resultlist.Add(new SelectListJSON() { Value = kvp.Key, Text = kvp.Value });
                        }
                    }
                }
                return Json(resultlist, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                var result = new List<SelectListJSON>();
                int i = 0;
                foreach (var item in WebCommon.ErrorListBuilder(ex))
                {
                    result.Add(new SelectListJSON { Value = (i++).ToString(), Text = ex.Message });
                }
                return Json(result, JsonRequestBehavior.AllowGet);
            }
        }
        #endregion ListOperations action

        #region PackagesMarking action
        /// <summary>
        /// Riport csomagok megjelölése akció.
        /// </summary>
        /// <param name="packagesMark">Melyik jelölést kell végrehajtani.</param>
        /// <param name="connectionString"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult PackagesMarking(PackagesMark packagesMark, string connectionString)
        {
            try
            {
                #region DEBUG
#if DEBUG
                string thisfn = $"{nameof(iSchedulerReportController)}.{nameof(PackagesMarking)}: ";
                System.Diagnostics.Debug.WriteLine($"{thisfn}packagesMark={packagesMark}, connectionString={connectionString}");
#endif
                #endregion DEBUG
                using (var dbc = new SchedulerReportDbContext(connectionString))
                {
                }
                return Json(new ReturnInfoJSON
                {
                    ReturnMessage = $"The \"{nameof(PackagesMarking)}\" action is coming soon. Still under construction. Mark={packagesMark}"
                }, JsonRequestBehavior.AllowGet); ;
            }
            catch (Exception ex)
            {
                return Json(new ReturnInfoJSON
                {
                    ReturnValue = -5,
                    ReturnMessage = string.Join(WebCommon.HTML_NEWLINE, WebCommon.ErrorListBuilder(ex))
                }, JsonRequestBehavior.AllowGet);
            }
        }
        #endregion PackagesMarking action

        #region Private methods (CheckIfParameterIsEmpty, SetError)

        private void CheckIfParameterIsEmpty(string par, string parName)
        {
            if (string.IsNullOrEmpty(par)) { ThrEx(typeof(SRWordCodes.iSchedulerReport.Operation.Messages.TheParameterIsRequired), parName); }
        }

        private void SetError(Type headWordCode, params object[] args)
        {
            ViewBag.Title = this.Mlmgt(typeof(GeneralWordCodes.MLM.General.Words.Error));
            ViewBag.Header = this.Mlmgt(headWordCode, args);
        }

        #endregion Private methods (CheckIfParameterIsEmpty, SetError)
    }
}