﻿using EpisodeInformer.Core.Threading;
using System;
using System.Drawing;
using System.Net;
using System.Threading;
using TvdbLib.Data;
using TvdbLib.Data.Banner;

namespace EpisodeInformer.Core.Browsing
{
    public sealed class TvdbLibBannerHelper
    {
        private const string apiKey = "F6ADE82DCB6FB30C";
        private Thread getBanner;

        public bool IsLoadingBanner
        {
            get
            {
                return this.getBanner != null && this.getBanner.IsAlive;
            }
        }

        public event delBannerLoaded BannerLoaded;

        public event EventHandler StoppedLoading;

        public event delErrorOccured ErrorOccured;

        public static Image GetThumbnail(TvdbBanner banner)
        {
            if (banner == null)
                return (Image)null;
            TvdbBannerWithThumb tvdbBannerWithThumb = (TvdbBannerWithThumb)banner;
            tvdbBannerWithThumb.LoadThumb();
            return tvdbBannerWithThumb.ThumbImage;
        }

        public void LoadBanner(TvdbBanner banner)
        {
            if (this.getBanner != null)
                this.getBanner.Abort();
            this.getBanner = new Thread(new ParameterizedThreadStart(this.doBanner));
            this.getBanner.Priority = ThreadPriority.AboveNormal;
            this.getBanner.Start((object)banner);
        }

        public void StopLoading()
        {
            if (this.getBanner != null)
                this.getBanner.Abort();
            if (this.StoppedLoading == null)
                return;
            this.StoppedLoading((object)this, EventArgs.Empty);
        }

        private void doBanner(object param)
        {
            try
            {
                TvdbBanner tvdbBanner = (TvdbBanner)param;
                tvdbBanner.LoadBanner(true);
                if (this.BannerLoaded == null)
                    return;
                ThreadingHelper.GetUIDispatcher().BeginInvoke((Delegate)this.BannerLoaded, new object[2]
        {
          (object) this,
          (object) tvdbBanner
        });
            }
            catch (ThreadAbortException ex)
            {
            }
            catch (WebException ex)
            {
            }
            catch (Exception ex)
            {
                if (this.ErrorOccured == null)
                    return;
                ThreadingHelper.GetUIDispatcher().BeginInvoke((Delegate)this.ErrorOccured, new object[2]
        {
          (object) this,
          (object) ex
        });
            }
        }
    }
}
