Source

Comicster / FileImport / FileImportTool.cs

using System.IO;
using System.Linq;
using System.Windows.Forms;
using Comicster.Tools;
using Comicster.Windows.Controls;

namespace Comicster.FileManagement
{
    public class FileImportTool : WorkerTool
    {
        private string folderPath;

        public override string Text
        {
            get { return "Import ComicInfo Archives..."; }
        }

        public override bool CanExecute(IToolContext context)
        {
            return context.Collection != null;
        }

        protected override bool PreExecute(IToolContext context)
        {
            var ofd = new FolderBrowserDialog()
            {
                ShowNewFolderButton = false,
            };

            if (ofd.ShowDialog() == DialogResult.OK)
            {
                folderPath = ofd.SelectedPath;
                return false;
            }
            return true;
        }

        protected override void ExecuteTask(IToolContext context)
        {
            var importer = new ComicvineImporter(context.Collection);
            foreach (string path in Directory.EnumerateFiles(folderPath, "*.cbz", SearchOption.AllDirectories))
            {
                if (count > 20)
                {
                    break;
                }
                var results = importer.Import(path);
                if (results != null)
                {
                    base.UpdateProgress(new ImportWorker(context, results.Item1, results.Item2).Work, path, "Success");
                    count++;
                }
                else
                {
                    base.UpdateProgress(null, path, "Failure");
                }
            }
        }

        private int count = 0;

        private class ImportWorker
        {
            private IToolContext context;
            private Title title;
            private Issue issue;

            public ImportWorker(IToolContext context, Title title, Issue issue)
            {
                this.context = context;
                this.title = title;
                this.issue = issue;
            }

            public void Work()
            {
                var collectionTitle = context.Collection.Owned.Titles.Where(x => x.Id == title.Id).FirstOrDefault();
                if (collectionTitle == null)
                {
                    context.Collection.Owned.Titles.Add(title);
                    collectionTitle = title;
                }
                collectionTitle.Issues.Add(issue);
                RebuildThumbnailsTool.UpdateThumbnail(issue);
                ThumbnailImage.Reload(issue.Id, issue.ImageSource);
                collectionTitle.NotifyIssuesChanged();
                context.SetModified();
            }
        }
    }
}