<commit_before>﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Microsoft.DotNet.ProjectModel;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NuGet.Frameworks;

namespace dotnet_new2
{
    public class TemplateManager
    {
        private ProjectContext _templatesProjectContext;
        private Project _templatesProject;

        // TODO: Don't Console.Write from this class, pass in a logger to write to or something and use pretty colors

        public TemplateManager()
            : this(GetTemplatesProject(GetDefaultTemplatesProjectFile()))
        {

        }

        public TemplateManager(ProjectContext templatesProjectContext)
        {
            _templatesProjectContext = templatesProjectContext;
            _templatesProject = templatesProjectContext.ProjectFile;
        }

        public bool InstallTemplatePackage(string packageId, string version)
        {
            // TODO: Validate the package ID and version

            // Add the dependency to the templates project file
            var projectFile = JObject.Parse(File.ReadAllText(_templatesProject.ProjectFilePath));
            var origProjectFile = projectFile.DeepClone();

            var dependencies = projectFile.Value<JObject>("dependencies");

            if (dependencies.Property(packageId) != null)
            {
                // Already installed!
                Console.WriteLine($"Template package {packageId} is already installed");
                return true;
            }

            dependencies.Add(packageId, new JValue(version));

            var json = projectFile.ToString();
            File.WriteAllText(_templatesProject.ProjectFilePath, json);

            if (!RestoreTemplatePackages())
            {
                // Error on restore! Rollback
                var origJson = origProjectFile.ToString();
                File.WriteAllText(_templatesProject.ProjectFilePath, origJson);

                Console.WriteLine($"Error installing template package {packageId}");
                return false;
            }

            Console.WriteLine($"Template package {packageId} installed");
            return true;
        }

        public bool UninstallTemplatePackage(string packageId)
        {
            // Remove the dependency from the templates project file
            var projectFile = JObject.Parse(File.ReadAllText(_templatesProject.ProjectFilePath));
            var origProjectFile = projectFile.DeepClone();

            var dependencies = projectFile.Value<JObject>("dependencies");

            if (dependencies.Property(packageId) != null)
            {
                dependencies.Remove(packageId);

                var json = projectFile.ToString();
                File.WriteAllText(_templatesProject.ProjectFilePath, json);

                if (!RestoreTemplatePackages())
                {
                    // Error on restore! Rollback
                    var origJson = origProjectFile.ToString();
                    File.WriteAllText(_templatesProject.ProjectFilePath, origJson);

                    Console.WriteLine($"Error uninstalling template package {packageId}");
                    return false;
                }
            }

            Console.WriteLine($"Template package {packageId} uninstalled");
            return true;
        }

        public IEnumerable<TemplatePackage> GetInstalledTemplates()
        {
            if (_templatesProjectContext.LockFile == null)
            {
                RestoreTemplatePackages();
                ReloadTemplatesProject();
            }

            var templatePackages = _templatesProjectContext.LockFile.PackageLibraries;
            var exporter = _templatesProjectContext.CreateExporter("Debug");
            var packages = exporter.GetAllExports().Select(e => e.Library).OfType<PackageDescription>();
            
            foreach (var package in packages)
            {
                var manifestFile = package.Library.Files.SingleOrDefault(f => f == "templates\\templates.json");
                if (manifestFile != null)
                {<commit_msg>Add TODO<commit_after>﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Microsoft.DotNet.ProjectModel;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NuGet.Frameworks;

namespace dotnet_new2
{
    public class TemplateManager
    {
        private ProjectContext _templatesProjectContext;
        private Project _templatesProject;

        // TODO: Don't Console.Write from this class, pass in a logger to write to or something and use pretty colors

        public TemplateManager()
            : this(GetTemplatesProject(GetDefaultTemplatesProjectFile()))
        {

        }

        public TemplateManager(ProjectContext templatesProjectContext)
        {
            _templatesProjectContext = templatesProjectContext;
            _templatesProject = templatesProjectContext.ProjectFile;
        }

        public bool InstallTemplatePackage(string packageId, string version)
        {
            // TODO: Validate the package ID and version

            // Add the dependency to the templates project file
            var projectFile = JObject.Parse(File.ReadAllText(_templatesProject.ProjectFilePath));
            var origProjectFile = projectFile.DeepClone();

            var dependencies = projectFile.Value<JObject>("dependencies");

            if (dependencies.Property(packageId) != null)
            {
                // Already installed!
                Console.WriteLine($"Template package {packageId} is already installed");
                return true;
            }

            dependencies.Add(packageId, new JValue(version));

            var json = projectFile.ToString();
            File.WriteAllText(_templatesProject.ProjectFilePath, json);

            if (!RestoreTemplatePackages())
            {
                // Error on restore! Rollback
                var origJson = origProjectFile.ToString();
                File.WriteAllText(_templatesProject.ProjectFilePath, origJson);

                Console.WriteLine($"Error installing template package {packageId}");
                return false;
            }

            Console.WriteLine($"Template package {packageId} installed");
            return true;
        }

        public bool UninstallTemplatePackage(string packageId)
        {
            // Remove the dependency from the templates project file
            var projectFile = JObject.Parse(File.ReadAllText(_templatesProject.ProjectFilePath));
            var origProjectFile = projectFile.DeepClone();

            var dependencies = projectFile.Value<JObject>("dependencies");

            if (dependencies.Property(packageId) != null)
            {
                dependencies.Remove(packageId);

                var json = projectFile.ToString();
                File.WriteAllText(_templatesProject.ProjectFilePath, json);

                if (!RestoreTemplatePackages())
                {
                    // Error on restore! Rollback
                    var origJson = origProjectFile.ToString();
                    File.WriteAllText(_templatesProject.ProjectFilePath, origJson);

                    Console.WriteLine($"Error uninstalling template package {packageId}");
                    return false;
                }
            }

            Console.WriteLine($"Template package {packageId} uninstalled");
            return true;
        }

        public IEnumerable<TemplatePackage> GetInstalledTemplates()
        {
            if (_templatesProjectContext.LockFile == null)
            {
                RestoreTemplatePackages();
                ReloadTemplatesProject();
            }

            var templatePackages = _templatesProjectContext.LockFile.PackageLibraries;
            var exporter = _templatesProjectContext.CreateExporter("Debug");
            var packages = exporter.GetAllExports().Select(e => e.Library).OfType<PackageDescription>();
            
            foreach (var package in packages)
            {
                var manifestFile = package.Library.Files.SingleOrDefault(f => f == "templates\\templates.json");

                // TODO: Handle other packages turning up in lock file due to template packages having dependencies
                if (manifestFile != null)
                {
{'fraction_non_alphanumeric': 0.07877280265339967, 'fraction_numerical': 0.00023691068467187872, 'mean_word_length': 2.0646098003629763, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 15, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '910305', 'n_tokens_mistral': 1909, 'n_tokens_neox': 1812, 'n_words': 452}