using ArtOfTest.Common.Win32;
using ArtOfTest.WebAii.Controls.HtmlControls;
using ArtOfTest.WebAii.Core;
using ArtOfTest.WebAii.TestTemplates;
using ArtOfTest.WebAii.Win32.Dialogs;

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Threading;
using System.Windows.Automation;
using ArtOfTest.Common.Extensions;
using System.Windows.Forms;
using System;

namespace MySampleTests
{
    /// <summary>
    /// Summary description for ScratchTestUnitTest
    /// </summary>
    [TestClass]
    public class ScratchTestUnitTest : BaseTest
    {

        #region [Setup / TearDown]
        public static string ActualMessage { get; private set; }
        public delegate void callmethod(Browser actvieBrowser);

        private TestContext testContextInstance = null;
        /// <summary>
        ///Gets or sets the VS test context which provides
        ///information about and functionality for the
        ///current test run.
        ///</summary>
        public TestContext TestContext
        {
            get
            {
                return testContextInstance;
            }
            set
            {
                testContextInstance = value;
            }
        }


        //Use ClassInitialize to run code before running the first test in the class
        [ClassInitialize()]
        public static void MyClassInitialize(TestContext testContext)
        {
        }


        // Use TestInitialize to run code before running each test
        [TestInitialize()]
        public void MyTestInitialize()
        {
            #region WebAii Initialization

            Initialize(false, this.TestContext.TestLogsDir, new TestContextWriteLine(this.TestContext.WriteLine));

            SetTestMethod(this, (string)TestContext.Properties["TestName"]);

            #endregion

        }

        // Use TestCleanup to run code after each test has run
        [TestCleanup()]
        public void MyTestCleanup()
        {

            //
            // Place any additional cleanup here
            //

            #region WebAii CleanUp

            // Shuts down WebAii manager and closes all browsers currently running
            // after each test. This call is ignored if recycleBrowser is set
            this.CleanUp();

            #endregion
        }

        //Use ClassCleanup to run code after all tests in a class have run
        [ClassCleanup()]
        public static void MyClassCleanup()
        {
            // This will shut down all browsers if
            // recycleBrowser is turned on. Else
            // will do nothing.
            ShutDown();
        }

        #endregion

        [TestMethod()]
        public void ScratchTest()
        {
            // Launch an instance of the browser
            Manager.Settings.UnexpectedDialogAction = UnexpectedDialogAction.DoNotHandle;
            Manager.LaunchNewBrowser(BrowserType.Chrome);

             
            //IE Handling
            //Setup dialog monitoring
            //AlertDialog confirmDialog = AlertDialog.CreateAlertDialog(ActiveBrowser, DialogButton.OK);
            //confirmDialog.HandlerDelegate = AlertDialogHandler;
            //Manager.DialogMonitor.AddDialog(confirmDialog);
            //Manager.DialogMonitor.Start();

            ActiveBrowser.NavigateTo("http://www.w3schools.com/js/tryit.asp?filename=tryjs_alert");
            ActiveBrowser.WaitUntilReady();


            var btnElement = Manager.ActiveBrowser.Frames["iframeResult"].Find.AllByTagName<HtmlControl>("button");
            btnElement[0].Click();
            /* Trial 1
            ConfirmDialog confirmDialog = ConfirmDialog.CreateConfirmDialog(Manager.Current.ActiveBrowser, DialogButton.OK);
            confirmDialog.HandlerDelegate = new DialogHandlerDelegate(this.ConfirmHandleDialog);
            Manager.Current.DialogMonitor.AddDialog(confirmDialog);
            Manager.Current.DialogMonitor.Start();           
            confirmDialog.WaitUntilHandled();
            Manager.Current.DialogMonitor.RemoveDialog(confirmDialog);
            Manager.Current.DialogMonitor.Stop();*/

             // As mentioned by Telerik team
            Manager.DialogMonitor.AddDialog(new AlertDialog(ActiveBrowser, DialogButton.OK));

            // Given that there were not dialog attribute set, the manager will not start the monitoring.
            // You need to invoke the monitoring
            Manager.DialogMonitor.Start();

            // Invoke an alert dialog
            Actions.InvokeScript("InvokeAlert()");



            ////Chrome Handling
            ////
            //callmethod obj = new callmethod(WebTest_CodedStep);

            //ActiveBrowser.NavigateTo("http://jabdwvc0558/Alert.html");
            ////ActiveBrowser.WaitUntilReady();
            //IAsyncResult tag = obj.BeginInvoke(this.ActiveBrowser, null, null);
            //Manager.ActiveBrowser.Find.AllByTagName<HtmlControl>("button")[0].Click(false);
            //System.Threading.Thread.Sleep(300);
            //obj.EndInvoke(tag);
            ////WebTest_CodedStep();
            ////System.Threading.Thread.Sleep(50);
            ////Manager.Desktop.KeyBoard.KeyPress(Keys.Space);

            ////System.Threading.Thread.Sleep(3000);
        }

        private void ConfirmHandleDialog(IDialog dialog)

        {

            ArtOfTest.WebAii.Win32.Button b = new ArtOfTest.WebAii.Win32.Button(dialog.Window, "OK", false);

            b.Click();

            dialog.HandleCount = 1;

            Manager.Current.DialogMonitor.RemoveDialog(dialog);

        }
        public static void AlertDialogHandler(IDialog dialog)
        {
            dialog.Window.WaitForVisibility(true, 15000);
            //IsMessageShown = true;
            ActualMessage = dialog.Window.AllChildren[2].Caption;
            dialog.Window.SetPosition(WindowPosition.TopMost);
            dialog.HandlerDelegate = null;
            dialog.Handle();
            dialog.Window.WaitForVisibility(false, 15000);
        }


        public static void WebTest_CodedStep(Browser actvieBrowser)
        {
            System.Threading.Thread.Sleep(100);

            AutomationElement dialogElement = AutomationElement.FromHandle(actvieBrowser.Window.Handle);

            AutomationElement chromeNode = dialogElement.GetControlFirstChild(el => el.Current.Name == "Google Chrome");

            if (chromeNode.GetControlNextSibling(el => el.Current.ControlType == ControlType.Custom) != null)
            {
                // for a VM machine

                dialogElement = chromeNode.GetControlNextSibling(el => el.Current.ControlType == ControlType.Custom);
            }
            else
            {
                // for a regular machines

                dialogElement = dialogElement.GetControlFirstChild(el => el.Current.ControlType == ControlType.Pane);
            }

            dialogElement = dialogElement.GetControlLastChild().GetControlLastChild();
            dialogElement = dialogElement.GetControlFirstChild().GetControlFirstChild().GetControlFirstChild().GetControlFirstChild().GetControlFirstChild();

            //Log dialog's text
           // Log.WriteLine(dialogElement.Current.Name);

           // handle the dialog
            //Manager.ActiveBrowser.Desktop.KeyBoard.KeyPress(Keys.Enter);
        }
    }
}