﻿using System;
using System.Diagnostics;
using System.IO;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;

namespace PepitaPackage
{
    public class CreatePackageTask : Task
    {
        public string NuGetBuildDirectory;
        [Required]
        public string MetadataAssembly { get; set; }
        public string TargetDir;
        public string Version;

        public override bool Execute()
        {
            var stopwatch = Stopwatch.StartNew();
            BuildEngine.LogMessageEvent(new BuildMessageEventArgs($"PepitaPackage (version {GetType().Assembly.GetName().Version}) Executing", "", "Pepita", MessageImportance.High));
            try
            {
                ValidatePackageDir();
                var runner = new Runner
                    {
                        PackageDirectory = NuGetBuildDirectory,
                        MetadataAssembly = MetadataAssembly,
                        Version = Version,
                        TargetDir = TargetDir,
                        WriteInfo = s => BuildEngine.LogMessageEvent(new BuildMessageEventArgs("\t" + s, "", "Pepita", MessageImportance.High)),
                    };
                    runner.Execute();
            }
            catch (ExpectedException expectedException)
            {
                BuildEngine.LogErrorEvent(new BuildErrorEventArgs("", "", "", 0, 0, 0, 0, $"Pepita: {expectedException.Message}", "", "Pepita"));
                return false;
            }
            catch (Exception exception)
            {
                BuildEngine.LogErrorEvent(new BuildErrorEventArgs("", "", "", 0, 0, 0, 0, $"Pepita: {exception}", "", "Pepita"));
                return false;
            }
            finally
            {
                stopwatch.Stop();
                BuildEngine.LogMessageEvent(new BuildMessageEventArgs($"\tFinished ({stopwatch.ElapsedMilliseconds}ms)", "", "Pepita", MessageImportance.High));
            }

            return true;
        }

        void ValidatePackageDir()
        {
            if (string.IsNullOrWhiteSpace(NuGetBuildDirectory))
            {
                throw new ExpectedException("Expected a path to the directory containing the nuget Files.");
            }
            if (!Directory.Exists(NuGetBuildDirectory))
            {
                throw new ExpectedException($"Could not find path '{NuGetBuildDirectory}'.");
            }
        }

    }
}