using System;
using System.Diagnostics;
using System.IO;
using Ursa.Controls;
using 常用工具集.Base;

namespace 常用工具集.ViewModel._04破解及系统相关
{
    public class 远程路径软链接ViewModel : ViewModelBase
    {
        public string RemotePath { get; set; } = "\\\\10.150.0.250\\运维软件";
        public string LocalPath { get; set; } = "d:\\运维软件";
        public DelegateCommand MakeLinkCmd { get; set; }

        public 远程路径软链接ViewModel()
        {
            MakeLinkCmd = new DelegateCommand(MakeLinkCmdFunc);
        }

        private void MakeLinkCmdFunc(object obj)
        {
            if (string.IsNullOrEmpty(LocalPath) || string.IsNullOrEmpty(RemotePath))
            {
                MessageBox.ShowAsync("请输入路径");
                return;
            }
            string remotePath = RemotePath;
            string localPath = LocalPath.Replace("/", "\\");
            bool flag = CreateSymbolicLink(remotePath, localPath);
            if (flag)
            {
                GlobalValues.Success("创建成功");
            }
            else
            {
                GlobalValues.Error("创建失败");
            }
        }

        private bool CreateSymbolicLink(string remotePath, string localPath)
        {
            try
            {
                Process process = new Process();
                ProcessStartInfo startInfo = new ProcessStartInfo
                {
                    FileName = "cmd.exe",
                    CreateNoWindow = true,
                    UseShellExecute = false,
                    RedirectStandardError = true,
                    RedirectStandardInput = true,
                    RedirectStandardOutput = true
                };
                process.StartInfo = startInfo;
                process.Start();
                process.StandardInput.WriteLine($"mklink /d {localPath} {remotePath}");
                process.StandardInput.AutoFlush = true;
                process.StandardInput.WriteLine("exit");
                StreamReader reader = process.StandardOutput;
                string ret = "";
                while (true)
                {
                    string curLine = reader.ReadLine();
                    ret = ret + curLine + "\r\n";
                    Console.WriteLine(curLine);
                    if (reader.EndOfStream)
                    {
                        break;
                    }
                }
                reader.Close();
                process.Close();
                if (ret.Contains("<<===>>"))
                    return true;
                return false;
            }
            catch
            {
                return false;
            }
        }
    }
}
