using Helpers.Log;
using log4net;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
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_IHConfiguration_reset_to_factory_defaults_api_factory_defaults_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("Setting system to ResetToFactoryDefaults mode."); 
            Response r = IhBoxSystemtConfiguration.SetSystemModeToResetToFactoryDefaults();

            success = r.Success; 

            if (r.Success)
            {
                logger.Debug("Starting timer to reset network cards and restarting system ...");
                new Thread(() =>
                {
                    Thread.Sleep(2000); 
                    IhBoxSystemtConfiguration.ResetNetworkCardsToAutomatic(restartInterfaces: false);
                    IhBoxSystemtConfiguration.RestartSystem();
                }).Start();
            }
        }catch(Exception ex){
            logger.Error("ResetToFactoryDefaults.", ex);
        }

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

}