using System;
using System.Collections.Generic;
using Quik.CommandMachine;
using Quik.Controls;
using Quik.Media;
using Quik.PAL;
using Quik.Typography;
namespace Quik
{
    /// 
    /// Main class for Quik applications.
    /// 
    public class QuikApplication
    {
        /// 
        /// The application platform driver.
        /// 
        public IQuikPlatform Platform { get; }
        /// 
        /// Title of the application.
        /// 
        public string Title
        {
            get => Platform.Title;
            set => Platform.Title = value;
        }
        /// 
        /// Application icon.
        /// 
        public QImage Icon
        {
            get => Platform.Icon;
            set => Platform.Icon = value;
        }
        public QuikPort MainPort { get; private set; } = null;
        public FontProvider FontProvider { get; }
        /// 
        /// List of media loaders, drivers that load media such as images and fonts.
        /// 
        public List MediaLoaders { get; } = new List();
        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 key, MediaHint hint)
        {
            IDisposable disposable = null;
            foreach (MediaLoader loader in MediaLoaders)
            {
                if (loader is MediaLoader 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);
                }
            }
        }
    }
}