/*
                   _ooOoo_
                  o8888888o
                  88" . "88
                  (| -_- |)
                  O\  =  /O
               ____/`---'\____
             .'  \\|     |//  `.
            /  \\|||  :  |||//  \
           /  _||||| -:- |||||-  \
           |   | \\\  -  /// |   |
           | \_|  ''\---/''  |   |
           \  .-\__  `-`  ___/-. /
         ___`. .'  /--.--\  `. . __
      ."" '<  `.___\_<|>_/___.'  >'"".
     | | :  `- \`.;`\ _ /`;.`/ - ` : | |
     \  \ `-.   \_ __\ /__ _/   .-` /  /
======`-.____`-.___\_____/___.-`____.-'======
                   `=---='
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
         佛祖保佑       永无BUG
*/
/************************************************************************************
* Copyright (c) 2014  All Rights Reserved. 
* CLR版本： 4.0.30319.35317 
* 创建人：  luoshupeng 
* 电子邮箱：luoshupeng@outlook.com 
* 创建时间：8/28/2014 4:18:22 PM 
* 描述： 解决方案版本转换
* ===================================================================== 
* 修改标记  
* 修改时间：8/28/2014 4:18:22 PM 
* 修改人： luoshupeng 
* 描述：   
************************************************************************************/

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace VSConverterLib
{
    public class SolutionConverter : IConverter
    {
        private string solutionPath;    //解决方案路径
        private bool isReady;           //解决方案是否准备好
        private List<ConversionResult> projectConversionResults = new List<ConversionResult>(); //项目转换结果
        private readonly Regex projectPathRegex = new Regex(@"Project.*,*,", RegexOptions.Compiled);

        public SolutionConverter()
        {
            //Initialize class
        }

        public SolutionConverter(string solutionPath)
        {
            this.Load(solutionPath);
        }

        public string SolutionName
        {
            get;
            private set;
        }

        public VisualStudioVersion VisualStudioVersion
        {
            get;
            private set;
        }

        public IdeVersion IDEVersion
        {
            get;
            private set;
        }

        public bool SaveAs
        {
            get;
            set;
        }

        public List<ConversionResult> ProjectConversionResults
        {
            get { return projectConversionResults; }
        }

        public bool Load(string solutionPath)
        {
            if (string.IsNullOrEmpty(solutionPath))
            {
                throw new ArgumentNullException("solutionPath can`t be null or empty.");
            }

            this.solutionPath = solutionPath;

            this.SolutionName = Path.GetFileNameWithoutExtension(solutionPath);
            this.VisualStudioVersion = GetStudioVersion(solutionPath);
            this.IDEVersion = GetIDEVersion(solutionPath);
            if (VisualStudioVersion != VisualStudioVersion.Unknown)
            {
                isReady = true;                
            }
            else
            {
                isReady = false;
            }

            return isReady;
        }


        public ConversionResult ConvertTo(VisualStudioVersion VSVersion)
        {
            return ConvertTo(VSVersion, IdeVersion.Default);
        }

        public ConversionResult ConvertTo(VisualStudioVersion VSVersion, IdeVersion IDEVersion)
        {
            ConversionResult result = new ConversionResult();
            result.ConverterReference = this;
            result.ConversionStatus = ConversionStatus.Succeeded;
            if (!isReady)
            {
                result.ConversionStatus = ConversionStatus.NotReady;
                return result;
            }

            TextReader tr = new StreamReader(this.solutionPath);
            string sln = tr.ReadToEnd();
            tr.Close();

            // 替换Visual Studio版本
            sln = sln.Replace(this.VisualStudioVersion.GetStringValue(), VSVersion.GetStringValue());

            // 替换IDE版本
            if (this.IDEVersion != IdeVersion.Default && IDEVersion != IdeVersion.Default)
            {
                string oldIDE = this.IDEVersion.GetStringValue() + " " + ((int)this.VisualStudioVersion).ToString();
                string newIDE = IDEVersion.GetStringValue() + " " + ((int)VSVersion).ToString();
                sln = sln.Replace(oldIDE, newIDE);
            }

            // 写新sln文件
            TextWriter tw = null;
            try
            {
                string newPath = this.solutionPath;
                if (this.SaveAs)
                {
                    string extensionName = Path.GetExtension(newPath);
                    newPath = newPath.Replace(extensionName, ((int)VSVersion).ToString() + extensionName);
                }
                tw = new StreamWriter(File.OpenWrite(newPath), Encoding.UTF8);
                tw.Write(sln);
            }
            catch (Exception)
            {
                result.ConversionStatus = ConversionStatus.Failed;
            }
            finally
            {
                this.isReady = false;
                if (tw != null)
                {
                    tw.Close();
                }
            }

            if (result.ConversionStatus == ConversionStatus.Succeeded)
            {
                ConvertProjects(VSVersion);
                result.ConversionStatus = ConversionStatus.Succeeded;
                if (this.projectConversionResults != null)
                {
                    foreach (ConversionResult ret in this.projectConversionResults)
                    {
                        if (ret.ConversionStatus != ConversionStatus.Succeeded)
                        {
                            result.ConversionStatus = ConversionStatus.Partial;
                            break;
                        }
                    }
                }
            }

            return result;
        }

        private VisualStudioVersion GetStudioVersion(string solutionPath)
        {
            VisualStudioVersion solutionVersion = VisualStudioVersion.Unknown;
            TextReader tr = new StreamReader(solutionPath);
            string sln = tr.ReadToEnd();
            tr.Close();

            foreach (VisualStudioVersion version in Enum.GetValues(typeof(VisualStudioVersion)))
            {
                if (sln.Replace(" ", "").Contains(version.ToString()) && sln.Contains(version.GetStringValue()))
                {
                    solutionVersion = version;
                    break;
                }
                else if (sln.Contains(version.GetStringValue()))
                {
                    solutionVersion = version;
                }
            }

            return solutionVersion;
        }

        private IdeVersion GetIDEVersion(string solutionPath)
        {
            IdeVersion ideVersion = IdeVersion.Default;
            TextReader tr = new StreamReader(solutionPath);
            string sln = tr.ReadToEnd();
            tr.Close();

            foreach (IdeVersion version in Enum.GetValues(typeof(IdeVersion)))
            {
                if (sln.Contains(version.GetStringValue()))
                {
                    ideVersion = version;
                    break;
                }
            }

            return ideVersion;
        }

        private void ConvertProjects(VisualStudioVersion VSVersion)
        {
            using (StreamReader reader = File.OpenText(this.solutionPath))
            {
                List<string> projectStrings = new List<string>();
                IConverter projectConverter;
                string projectName, path;
                int index;

                // A bit messy, but gets the job done.
                // Retrieve the actual path of the solution.
                path = this.solutionPath.Remove(this.solutionPath.IndexOf(Path.GetFileName(this.solutionPath)), Path.GetFileName(this.solutionPath).Length);
                this.projectConversionResults.Clear();

                // Selects all the strings that contain the "Project("{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}") = "Name", "Name\Name.xxproj","
                // signature.
                projectStrings.AddRange(from Match match in this.projectPathRegex.Matches(reader.ReadToEnd())
                                        where match.Success
                                        select match.Value);

                // Here we attempt to convert all the projects and save the conversion results.
                foreach (string projectString in projectStrings)
                {
                    // Cut string down to only contain the solution relative path.
                    projectName = projectString.TrimEnd(new char[] { ' ', ',', '\"' });
                    index = projectName.LastIndexOf('\"') + 1;
                    projectName = path + projectName.Substring(index, projectName.Length - index);
                    projectConverter = null;

                    // Make sure we don't crash the program by trying to convert a Visual C++ project
                    if (!Path.GetExtension(projectName).Contains("vc"))
                    {
                        projectConverter = new ProjectConverter(projectName);
                        projectConverter.SaveAs = this.SaveAs;
                    }
                    else
                    {
                        // Reserved for a Visual C++ Project converter here.
                    }

                    if (projectConverter != null)
                    {
                        this.projectConversionResults.Add(projectConverter.ConvertTo(VSVersion));
                    }
                }
            }
        }
    }
}
