using System;

namespace ZionExtractor.Controllers.Validation
{
    class CallScript
    {
        public static bool ExecuteValidationVBScript(string script, string value)
        {
            string tmpFileName =
                string.Format(@"{0}\{1}", System.Environment.GetEnvironmentVariable("TEMP"),
                DateTime.Now.ToString("yyyyMMddHHmmssfff").GetHashCode().ToString() + ".vbs");
            if (System.IO.File.Exists(script))
            {
                System.IO.File.WriteAllText("", script);
                script = string.Format(@"{0}\{1}", System.Environment.GetEnvironmentVariable("TEMP"), script);
            }

            string cmd = string.Format("{0} {1}", script, value);

            System.Diagnostics.Process process = new System.Diagnostics.Process();
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.CreateNoWindow = true;
            process.StartInfo.FileName = @"cscript";
            process.StartInfo.Arguments = cmd;
            try
            {
                process.Start();
                process.StandardOutput.ReadToEnd();

                if (System.IO.File.Exists(tmpFileName))
                    System.IO.File.Delete(tmpFileName);

                if (process.ExitCode == 1)
                {
                    return true;
                }
                return false;
            }
            catch (Exception)
            {
                if (System.IO.File.Exists(tmpFileName))
                    System.IO.File.Delete(tmpFileName);
                throw new Exception("Invalid script or parameter");
            }
        }
    }
}
