using Helpers.Log;
using log4net;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.ServiceProcess;
using System.Threading;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class app_custom_screens_modules_OEE_OEEConfiguration_reset_to_factory_defaults_oee_api_factory_defaults_oee_api : System.Web.UI.Page
{
    private JavaScriptSerializer jss = new JavaScriptSerializer();
    private ILog logger = Logger.GetLogger(MethodBase.GetCurrentMethod().DeclaringType.Name);

    protected void Page_Load(object sender, EventArgs e)
    {
        object response = null;

        try
        {
            string action = Request.Form["action"];

            if (action != null)
            {
                switch (action.ToString().ToUpper())
                {
                    case "RESET_TO_FACTORY_DEFAULTS":
                        response = this.ResetToFactoryDefaults();
                        break;
                }
            }
            else
            {
                response = new Response
                {
                    Success = false,
                    Message = "Parameter 'Action' can not be empty or null.",
                };
            }
        }
        catch (Exception ex)
        {
            response = new Response
            {
                Success = false,
                Message = ex.Message,
            };

            this.logger.Error(ex);
        }

        Response.Clear();
        Response.ContentType = "application/json; charset=utf-8";
        Response.Write(jss.Serialize(response));
        Response.End();
    }

    private Response ResetToFactoryDefaults()
    {
        bool success = false;
        try
        {
            logger.Debug("Reseting OEE to factory defaults.");

            bool serviceManageFailed = false;
            ServiceController[] allServCtrl = ServiceController.GetServices();
            List<ServiceController> servCtrlToStop = new List<ServiceController>();
            TimeSpan serviceHandlingTimeout = new TimeSpan(0, 1, 0);

            String internalPath = "app\\custom-screens\\modules\\oee\\oee-report\\cube-api\\";
            String path = AppDomain.CurrentDomain.BaseDirectory + internalPath;
            String cubeFullPath = path + "cube\\cube.cub";

            logger.DebugFormat("Deleting cube file '{0}' to reset OEE to factory defaults.", cubeFullPath);

            if (File.Exists(cubeFullPath) == true)
                File.Delete(cubeFullPath);


            logger.Debug("Getting cube procesing services to reset OEE to factory defaults.");

            //Get reference of all Industrial Historian Cube Processing windows services.
            foreach (ServiceController servCtrl in allServCtrl)
            {
                if (servCtrl.DisplayName.StartsWith("Industrial Historian Cube Processing", StringComparison.OrdinalIgnoreCase) == true)
                    servCtrlToStop.Add(servCtrl);
            }

            servCtrlToStop = servCtrlToStop
                        .OrderByDescending(servCtrl => servCtrl.DisplayName)
                        .ToList();

            logger.DebugFormat("Restarting '{0}' cube procesing services to reset OEE to factory defaults.", servCtrlToStop.Count);

            servCtrlToStop.ForEach(servCtrl =>
            {
                try
                {
                    logger.Debug(string.Format("Cube procesing service '{0}' status: {1}.", servCtrl.DisplayName, servCtrl.Status));

                    if ((servCtrl.Status != ServiceControllerStatus.Stopped) && (servCtrl.Status != ServiceControllerStatus.StopPending))
                    {
                        logger.Debug(string.Format("Stopping cube procesing service '{0}'.", servCtrl.DisplayName));

                        servCtrl.Stop();

                        servCtrl.WaitForStatus(ServiceControllerStatus.Stopped, serviceHandlingTimeout);
                    }

                    logger.Debug(string.Format("Cube procesing service '{0}' status: {1}.", servCtrl.DisplayName, servCtrl.Status));

                    if ((servCtrl.Status != ServiceControllerStatus.Running) && (servCtrl.Status != ServiceControllerStatus.StartPending))
                    {
                        logger.Debug(string.Format("Starting cube procesing service '{0}'.", servCtrl.DisplayName));

                        servCtrl.Start();

                        servCtrl.WaitForStatus(ServiceControllerStatus.Running, serviceHandlingTimeout);
                    }
                }
                catch (Exception ex)
                {
                    serviceManageFailed = true;

                    logger.Error(ex);
                }
            });

            logger.Debug("Restarted cube procesing services.");

            success = !serviceManageFailed;
        }
        catch (Exception ex)
        {
            logger.Error("ResetToFactoryDefaultsOEE.", ex);
        }

        return new Response() { Success = success };
    }
}