﻿﻿/*
    The MIT License (MIT)
  
    Copyright (c) 2015 Mehmetali Shaqiri (mehmetalishaqiri@gmail.com)
  
    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:
    The above copyright notice and this permission notice shall be included in all
    copies or substantial portions of the Software.
    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
    SOFTWARE. 
 */


using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.VersionControl.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;

namespace NugetServer.Cleanup.Tfs
{
    public class CollectionFactory : ICollectionFactory
    {
        private readonly string _collection = ConfigurationManager.AppSettings["Collection"];

        public List<string> GetInstalledPackages()
        {
            var teamProjectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(_collection));
            var versionControlServer = teamProjectCollection.GetService<VersionControlServer>();
            var projects = GetTfsProjects(new Uri(_collection));
            var installedPackages = new List<string>();


            foreach (var project in projects)
            {
                var items = versionControlServer.GetItems(String.Format(@"$\{0}", project.Name),RecursionType.Full);
                
                var packageFiles = items.Items.Where(f => f.ServerItem.Contains("packages.config")).ToList();
                foreach (var item in packageFiles)
                {
                    
                    var tfsFile = versionControlServer.GetItem(item.ServerItem, VersionSpec.Latest);
                    
                    using (var stream = item.DownloadFile())
                    {
                        using (var memoryStream = new MemoryStream())
                        {
                            stream.CopyTo(memoryStream);

                            // Use StreamReader to read MemoryStream created from byte array
                            using (var streamReader = new StreamReader(new MemoryStream(memoryStream.ToArray())))
                            {
                                var packageContent = streamReader.ReadToEnd();

                                var xdoc = XDocument.Parse(packageContent);
                                installedPackages.AddRange(from lv1 in xdoc.Descendants("package")
                                                            select
                                                                lv1.Attribute("id").Value.ToString() + "." +
                                                                lv1.Attribute("version").Value.ToString());
                            }
                        }
                    }
                }
            }
            return installedPackages;
        }


        private IEnumerable<Project> GetTfsProjects(Uri tpcAddress)
        {
            var tpc = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(tpcAddress);

            tpc.Authenticate();

            var workItemStore = new WorkItemStore(tpc);
            var projectList = (from Project pr in workItemStore.Projects select pr).ToList();

            return projectList;
        }
    
    }
}
