﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BotVentic.Plugins
{
    public class IPluginWrapper
    {
        private bool _isLoaded;
        private bool _enabled;

        public string FileName { get; set; }
        public IPlugin Plugin { get; set; }

        public IPluginWrapper()
        {
            _isLoaded = true;
        }

        public IPluginWrapper(string filename, IPlugin plugin)
        {
            FileName = filename;
            Plugin = plugin;
        }

        public string Name => Plugin != null ? Plugin.Name : FileName;
        public string NameAndVersion => Name + " " + (Plugin?.Version.ToString() ?? "");

        public bool IsEnabled
        {
            get { return _enabled; }
            set
            {
                _enabled = value;
                if (value)
                {
                    if (!_isLoaded)
                    {
                        var canLoad = Load();
                        Console.WriteLine("Enabled " + Name);
                        if (!canLoad)
                            return;

                    }
                    foreach (var p in Program.Config.Plugins)
                    {
                        if (p.Name == Name)
                        {
                            p.Enabled = true;
                            break;
                        }
                    }
                }
                else
                {
                    if (_isLoaded)
                    {
                        Unload();
                        Console.WriteLine("Disabled " + Name);
                    }
                    foreach (var p in Program.Config.Plugins)
                    {
                        if (p.Name == Name)
                        {
                            p.Enabled = false;
                            break;
                        }
                    }
                }
            }
        }

        public bool Load()
        {
            if (Plugin == null || !IsEnabled)
                return false;
            try
            {
                Plugin.OnLoad();
            }
            catch (Exception e)
            {
                Console.WriteLine(string.Format("There was an error loading plugin {0}. Reason: {1}", Name, e.Message));
                return false;
            }
            _isLoaded = true;
            return true;
        }

        public void Unload()
        {
            if (Plugin == null || !IsEnabled)
                return;
            try
            {
                Plugin.OnUnload();
            }
            catch (Exception e)
            {
                Console.WriteLine(string.Format("There was an error unloading plugin {0}. Reason: {1}", Name, e.Message));
            }
            _isLoaded = false;
        }
    }
}