using Ascon.Pilot.BimConverters.Core;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.IO;
using Ascon.Pilot.DataClasses;
using Newtonsoft.Json;
using File = Pri.LongPath.File;
using Path = Pri.LongPath.Path;

namespace CommandLineIfcConverter
{
    [Export(typeof(IConverterToIfc))]
    public class CommandLineIfcConverter : IConverterToIfc
    {
        private CmdSettings _settings = LoadSettings();

        private static CmdSettings LoadSettings()
        {
            var location = typeof(CmdSettings).Assembly.Location;
            var jsonSettingsPath = Path.Combine(Path.GetDirectoryName(location), "cmdsettings.json");
            
            var serializer = new JsonSerializer();
            using (var stream = File.OpenRead(jsonSettingsPath))
            using (var streamReader = new StreamReader(stream))
            using (var jsonReader = new JsonTextReader(streamReader))
            {
                return serializer.Deserialize<CmdSettings>(jsonReader);
            }
        }

        public bool IsConverterInstalled()
        {
            return _settings.IsEnabled;
        }

        public void Initialize()
        {

        }

        public string Convert(ConverterRequest request)
        {
            var tempFilePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + ".ifc");
            var args = string.Format(_settings.Args, request.Path, tempFilePath);
            var startInfo = new ProcessStartInfo
            {
                FileName = _settings.Process,
                Arguments = args,
                UseShellExecute = false,
                RedirectStandardOutput = false,
                RedirectStandardError = false,
                RedirectStandardInput = false,
                CreateNoWindow = false
            };

            using (var process = new Process())
            {
                process.StartInfo = startInfo;
                process.Start();
                process.WaitForExit();

                if (process.ExitCode != 0)
                    return null;
            }
            return tempFilePath;
        }

        public string Name => _settings.Name;
        public IEnumerable<DRule> Rules => new[]
        {
            new DRule
            {
                Id = new Guid("{90C6E2AC-90DC-4D28-AC29-944664B3F17B}"),
                ChangeType = ChangeType.Create,
                FileExtension = _settings.FileExtension
            },
            new DRule
            {
                Id = new Guid("{945814BF-D60F-425D-9BA3-2CA6B0C388B0}"),
                ChangeType = ChangeType.Update,
                FileExtension = _settings.FileExtension
            }
        };

        public IEnumerable<ConverterSettingDescriptor> Settings => Array.Empty<ConverterSettingDescriptor>();

        public void Dispose()
        {
        }
    }
}
