using System;
using System.Collections.Generic;
using Quik.CommandMachine;
using Quik.Controls;
using Quik.Media;
using Quik.PAL;
using Quik.Typography;

namespace Quik
{
    /// <summary>
    /// Main class for Quik applications.
    /// </summary>
    public class QuikApplication
    {
        /// <summary>
        /// The application platform driver.
        /// </summary>
        public IQuikPlatform Platform { get; }

        /// <summary>
        /// Title of the application.
        /// </summary>
        public string Title
        {
            get => Platform.Title;
            set => Platform.Title = value;
        }

        /// <summary>
        /// Application icon.
        /// </summary>
        public QImage Icon
        {
            get => Platform.Icon;
            set => Platform.Icon = value;
        }

        public QuikPort MainPort { get; private set; } = null;

        public FontProvider FontProvider { get; }

        /// <summary>
        /// List of media loaders, drivers that load media such as images and fonts.
        /// </summary>
        public List<MediaLoader> MediaLoaders { get; } = new List<MediaLoader>();

        public QuikApplication(IQuikPlatform platform)
        {
            Platform = platform;
            FontProvider = new FontProvider(this);
        }

        public IDisposable GetMedia(object key, MediaHint hint)
        {
            IDisposable disposable = null;

            foreach (MediaLoader loader in MediaLoaders)
            {
                disposable = loader.GetMedia(key, hint);

                if (disposable != null)
                    break;
            }

            return disposable;
        }

        public IDisposable GetMedia<T>(T key, MediaHint hint)
        {
            IDisposable disposable = null;

            foreach (MediaLoader loader in MediaLoaders)
            {
                if (loader is MediaLoader<T> typedLoader)
                {
                    disposable = typedLoader.GetMedia(key, hint);

                    if (disposable != null)
                        break;
                }
            }

            return disposable;
        }

        public void Run(View mainView)
        {
            MainPort = new QuikPort(Platform) { UIElement = mainView };
            CommandList cmd = new CommandList();

            MainPort.EventRaised += (sender, ea) => mainView.NotifyEvent(sender, ea);

            while (MainPort.IsValid)
            {
                Platform.ProcessEvents(false);
                if (MainPort.IsValid)
                {
                    cmd.Clear();
                    MainPort.Paint(cmd);
                }
            }
        }
    }
}