using System;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows;

using FasdDesktopUi.Basics.UserControls;
using C4IT.FASD.Base;
using static C4IT.Logging.cLogManager;

namespace FasdDesktopUi.Basics.UiActions
{
    public class cUiCopyAction : cUiActionBase
    {
        public cCopyTemplate CopyTemplate { get; set; }

        public cUiCopyAction(cCopyTemplate copyTemplate)
        {
            CopyTemplate = copyTemplate;
        }

        public override async Task<bool> RunUiActionAsync(object sender, UIElement UiLocation, bool isDetailedLayout, cSupportCaseDataProvider dataProvider)
        {
            var CM = MethodBase.GetCurrentMethod();
            LogMethodBegin(CM);
            try
            {
                if (dataProvider == null || dataProvider.NamedParameterEntries.Count == 0 || CopyTemplate == null)
                    return false;

                var ClData = new DataObject();
                foreach (var Entry in CopyTemplate.CopyContentList.Values)
                    SetCopyContent(ClData, Entry, dataProvider);

                System.Windows.Forms.Clipboard.SetDataObject(ClData, true);

                if (sender is CustomMenuItem senderElement)
                    await cUtility.ChangeIconToCheckAsync(senderElement.MenuItemIcon);

                return true;
            }
            catch (Exception E)
            {
                LogException(E);
            }
            finally
            {
                LogMethodEnd(CM);
            }

            return false;
        }

        private void SetCopyContent(DataObject ClData, cCopyContent Content, cSupportCaseDataProvider dataProvider)
        {
            var clipboardText = Content.Content;

            clipboardText = dataProvider.HealthCardDataHelper.ReplaceNamedParameters(clipboardText, Content.Format == enumCopyContentFormat.HTML);

            var textFormat = TextDataFormat.UnicodeText;
            if (Content.Format == enumCopyContentFormat.HTML)
            {
                clipboardText = cUtility.GetHtmlFrame(clipboardText);
                textFormat = TextDataFormat.Html;
            }

            ClData.SetText(clipboardText, textFormat);
        }

    }
}
