public FtpAssetsControl(MainWindow main, BoxartControl boxart, BackgroundControl background, IconBannerControl iconBanner, ScreenshotsControl screenshots)
 {
     InitializeComponent();
     _main = main;
     _boxart = boxart;
     _background = background;
     _iconBanner = iconBanner;
     _screenshots = screenshots;
     App.FtpOperations.StatusChanged += (sender, args) => Dispatcher.Invoke(new Action(() => Status.Text = args.StatusMessage));
     FtpAssetsBox.ItemsSource = _assetsList;
     if(!App.FtpOperations.HaveSettings) {
         var ip = GetActiveIp();
         var index = ip.LastIndexOf('.');
         if(ip.Length > 0 && index > 0)
             IpBox.Text = ip.Substring(0, index + 1);
         }
     else {
         IpBox.Text = App.FtpOperations.IpAddress;
         UserBox.Text = App.FtpOperations.Username;
         PassBox.Text = App.FtpOperations.Password;
         PortBox.Text = App.FtpOperations.Port;
         }
 }
        public LocalAssetsControl(MainWindow main, BoxartControl boxart, BackgroundControl background, IconBannerControl iconBanner, ScreenshotsControl screenshots)
        {
            InitializeComponent();
            _main = main;
            _boxart = boxart;
            _background = background;
            _iconBanner = iconBanner;
            _screenshots = screenshots;

            FtpAssetsBox.ItemsSource = _assetsList;

            onlyNewSync.IsChecked = Settings.Default.OnlyNew;
            sliderScreens.Value = Settings.Default.NumScreens;

            #region Xbox.com Worker

            _xboxWorker.WorkerReportsProgress = true;
            _xboxWorker.WorkerSupportsCancellation = true;

            var xboxMarketDataResult = new ConcurrentBag<XboxTitleInfo>();
            var omitedTitles = new ConcurrentBag<AuroraDbManager.ContentItem>();

            _xboxWorker.DoWork += (sender, args) => {

                var bgWork = sender as BackgroundWorker;

                try {

                    if(_assetsList.Count ==0) {
                        Dispatcher.Invoke(new Action(() => Status.Text = "No games..."));
                        return;
                        }

                    xboxMarketDataResult = new ConcurrentBag<XboxTitleInfo>();
                    omitedTitles = new ConcurrentBag<AuroraDbManager.ContentItem>();
                    XboxLocale loc = args.Argument as XboxLocale;

                    var _assetsToGo = _assetsList.Where(p => p.TitleIdNumber > 0);

                    Dispatcher.Invoke(new Action(() => _main.busyProgress.Visibility = Visibility.Visible));
                    Dispatcher.Invoke(new Action(() => _main.busyProgress.Text= "0 / " + _assetsToGo.Count()));

                    var maxScreens = Settings.Default.NumScreens;

                    int progressCount = 0;
                    Object progressLock = new Object();

                    Ts.Parallel.ForEach(_assetsToGo, (contentItem) => {

                        if(bgWork.CancellationPending) {
                            args.Cancel = true;
                            }

                        XboxTitleInfo _titleResult = _xboxAssetDownloader.GetTitleInfoSingle(contentItem.TitleIdNumber, loc);

                        if(_titleResult.AssetsInfo!= null) {

                            var unityCovers = XboxUnity.GetUnityCoverInfo(contentItem.TitleId);

                            if(unityCovers.Count() > 0) {
                                var cover = unityCovers.FirstOrDefault(p => p._unityResponse.Official == true);
                                if(cover!= null) {
                                    _titleResult.CoverAsset = cover;
                                    }
                                }

                            xboxMarketDataResult.Add(_titleResult);
                            }
                        else {
                            omitedTitles.Add(contentItem);
                            }

                        lock (progressLock) {
                            bgWork.ReportProgress(1, (++progressCount) + " / " + _assetsToGo.Count());
                            }
                    });

                    progressCount = 0;

                    Ts.Parallel.ForEach(xboxMarketDataResult, (titleItem) => {
                        AuroraDbManager.ContentItem contentItem = _assetsToGo.FirstOrDefault(p => p.TitleId == titleItem.TitleId);
                        if(contentItem!= null) {

                            lock (progressLock) {
                                bgWork.ReportProgress(1, (++progressCount) + " / " + xboxMarketDataResult.Count);
                                }

                            var itemWrap = new ContentItemLocal(contentItem);

                            if(titleItem.CoverAsset!= null) {

                                var assetFileC = new AuroraAsset.AssetFile();

                                assetFileC.SetBoxart(titleItem.CoverAsset.GetCover(), true);

                                itemWrap.SaveAsBoxart(assetFileC.FileData);

                                assetFileC.Dispose();
                                }

                            int screenCount = 0;

                            Ts.Parallel.ForEach(titleItem.AssetsInfo, (assetInfo) => {

                                if(!assetInfo.HaveAsset) {

                                    if(assetInfo.AssetType == XboxTitleInfo.XboxAssetType.Screenshot && screenCount >= maxScreens) {
                                        return;
                                        }
                                    var XboxAsset = assetInfo.GetAsset();
                                    var assetFile = new AuroraAsset.AssetFile();

                                    switch(assetInfo.AssetType) {
                                        case XboxTitleInfo.XboxAssetType.Icon:
                                        assetFile.SetIcon(XboxAsset.Image, true);
                                        itemWrap.SaveAsIconBanner(assetFile.FileData);
                                        break;
                                        case XboxTitleInfo.XboxAssetType.Banner:
                                        assetFile.SetBanner(XboxAsset.Image, true);
                                        itemWrap.SaveAsIconBanner(assetFile.FileData);
                                        break;
                                        case XboxTitleInfo.XboxAssetType.Background:
                                        assetFile.SetBackground(XboxAsset.Image, true);
                                        itemWrap.SaveAsBackground(assetFile.FileData);
                                        break;
                                        case XboxTitleInfo.XboxAssetType.Screenshot:
                                        // _screenshots.Load(XboxAsset.Image, false);
                                        // itemWrap.SaveAsScreenshots(assetFile.FileData);
                                        screenCount++;
                                        break;
                                        default:
                                        break;
                                        }
                                    //  XboxAsset.Dispose();
                                    assetFile.Dispose();

                                    }

                                GC.Collect();

                            });

                            }
                        titleItem.Dispose();
                    });

                    Dispatcher.Invoke(new Action(() => Status.Text = "Finished downloading asset information..."));

                    }
                catch(Exception ex) {
                    MainWindow.SaveError(ex);
                    Dispatcher.Invoke(new Action(() => Status.Text = "An error has occured, check error.log for more information..."));
                    }
            };
            _xboxWorker.RunWorkerCompleted += (sender, args) => {

                _main.busyProgress.Visibility = Visibility.Collapsed;
                _main.BusyIndicator.Visibility = Visibility.Collapsed;
                syncDb.IsEnabled = true;

                if(omitedTitles.Count >0) {

                    var logPath = Path.GetTempPath() + Path.DirectorySeparatorChar + "omittedTitlesLog.log";

                    string logcontent = "";
                    foreach(var item in omitedTitles) {
                        logcontent += "Title name: " + item.TitleName + @"

            TitleID: " + item.TitleId + @"

            Title int: " + item.TitleIdNumber + @"

            MediaID: " + item.MediaId + @"
            -----------------------------------------------

            ";
                        }

                    File.WriteAllText(logPath, logcontent);

                    var msgresult = MessageBox.Show("Omitted titles " + omitedTitles.Count + @"

            Show log?", "Action", MessageBoxButton.OKCancel, MessageBoxImage.Information, MessageBoxResult.Cancel);

                    if(msgresult == MessageBoxResult.OK) {
                        try {
                            Process.Start(logPath);
                            }
                        catch {

                            }
                        }

                    }
                // var disp = new List<XboxTitleInfo.XboxAssetInfo>();

            };

            _xboxWorker.ProgressChanged+=_xboxWorker_ProgressChanged;

            #endregion
        }
        public OnlineAssetsControl(MainWindow main, BoxartControl boxart, BackgroundControl background, IconBannerControl iconBanner, ScreenshotsControl screenshots)
        {
            InitializeComponent();
            XboxAssetDownloader.StatusChanged += StatusChanged;
            _main = main;
            _boxart = boxart;
            _background = background;
            _iconBanner = iconBanner;
            _screenshots = screenshots;
            SourceBox.SelectedIndex = Settings.Default.OnlineSourceIndex;

            #region Xbox.com Locale worker

            var bw = new BackgroundWorker();
            bw.DoWork += LocaleWorkerDoWork;
            bw.RunWorkerCompleted += (sender, args) => {
                LocaleBox.ItemsSource = _locales;
                SourceBox.Items.Add("Xbox.com");
                var index = 0;
                for(var i = 0;i < _locales.Length;i++) {
                    if(!_locales[i].Locale.Equals("en-us", StringComparison.CurrentCultureIgnoreCase))
                        continue;
                    index = i;
                    break;
                    }

                if(Settings.Default.LocaleMarketIndex == -99) {
                    Settings.Default.LocaleMarketIndex = index;
                    Settings.Default.LocaleMarketName = "en-us";
                    }

                LocaleBox.SelectedIndex = Settings.Default.LocaleMarketIndex;
                Settings.Default.Save();
            };
            bw.RunWorkerAsync();

            #endregion

            #region Unity Worker

            _unityWorker.DoWork += (o, args) => {
                try {
                    _unityResult = XboxUnity.GetUnityCoverInfo(args.Argument.ToString());
                    Dispatcher.Invoke(new Action(() => StatusMessage.Text = "Finished downloading asset information..."));
                    args.Result = true;
                    }
                catch(Exception ex) {
                    MainWindow.SaveError(ex);
                    Dispatcher.Invoke(new Action(() => StatusMessage.Text = "An error has occured, check error.log for more information..."));
                    args.Result = false;
                    }
            };
            _unityWorker.RunWorkerCompleted += (o, args) => {
                if((bool)args.Result) {
                    ResultBox.ItemsSource = _unityResult;
                    SearchResultCount.Text = _unityResult.Length.ToString(CultureInfo.InvariantCulture);
                    }
                else {
                    ResultBox.ItemsSource = null;
                    SearchResultCount.Text = "0";
                    }
            };

            #endregion

            #region Xbox.com Worker

            _xboxWorker.DoWork += (sender, args) => {
                try {
                    _xboxResult = _keywords == null
                                      ? _xboxAssetDownloader.GetTitleInfo(_titleId, args.Argument as XboxLocale)
                                      : _xboxAssetDownloader.GetTitleInfo(_keywords, args.Argument as XboxLocale);
                    Dispatcher.Invoke(new Action(() => StatusMessage.Text = "Finished downloading asset information..."));
                    args.Result = true;
                    }
                catch(Exception ex) {
                    MainWindow.SaveError(ex);
                    Dispatcher.Invoke(new Action(() => StatusMessage.Text = "An error has occured, check error.log for more information..."));
                    args.Result = false;
                    }
            };
            _xboxWorker.RunWorkerCompleted += (sender, args) => {
                if((bool)args.Result) {
                    var disp = new List<XboxTitleInfo.XboxAssetInfo>();
                    foreach(var info in _xboxResult)
                        disp.AddRange(info.AssetsInfo);
                    ResultBox.ItemsSource = disp;
                    SearchResultCount.Text = disp.Count.ToString(CultureInfo.InvariantCulture);
                    }
                else {
                    ResultBox.ItemsSource = null;
                    SearchResultCount.Text = "0";
                    }
            };

            #endregion

            #region Cover Menu

            _coverMenu = new UIElement[] {
                                             new MenuItem {
                                                              Header = "Save cover to file"
                                                          },
                                             new MenuItem {
                                                              Header = "Set as cover"
                                                          }
                                         };
            ((MenuItem)_coverMenu[0]).Click += (sender, args) => MainWindow.SaveToFile(_img, "Select where to save the cover", "cover.png");
            ((MenuItem)_coverMenu[1]).Click += (sender, args) => _boxart.Load(_img);

            #endregion

            #region Icon Menu

            _iconMenu = new UIElement[] {
                                            new MenuItem {
                                                             Header = "Save icon to file"
                                                         },
                                            new MenuItem {
                                                             Header = "Set as icon"
                                                         }
                                        };
            ((MenuItem)_iconMenu[0]).Click += (sender, args) => MainWindow.SaveToFile(_img, "Select where to save the icon", "icon.png");
            ((MenuItem)_iconMenu[1]).Click += (sender, args) => _iconBanner.Load(_img, true);

            #endregion

            #region Banner Menu

            _bannerMenu = new UIElement[] {
                                              new MenuItem {
                                                               Header = "Save banner to file"
                                                           },
                                              new MenuItem {
                                                               Header = "Set as banner"
                                                           }
                                          };
            ((MenuItem)_bannerMenu[0]).Click += (sender, args) => MainWindow.SaveToFile(_img, "Select where to save the banner", "banner.png");
            ((MenuItem)_bannerMenu[1]).Click += (sender, args) => _iconBanner.Load(_img, false);

            #endregion

            #region Background Menu

            _backgroundMenu = new UIElement[] {
                                                  new MenuItem {
                                                                   Header = "Save background to file"
                                                               },
                                                  new MenuItem {
                                                                   Header = "Set as background"
                                                               }
                                              };
            ((MenuItem)_backgroundMenu[0]).Click += (sender, args) => MainWindow.SaveToFile(_img, "Select where to save the background", "background.png");
            ((MenuItem)_backgroundMenu[1]).Click += (sender, args) => _background.Load(_img);

            #endregion

            #region Screenshots Menu

            _screenshotsMenu = new UIElement[] {
                                                   new MenuItem {
                                                                    Header = "Save screenshot to file"
                                                                },
                                                   new MenuItem {
                                                                    Header = "Replace current screenshot"
                                                                },
                                                   new MenuItem {
                                                                    Header = "Add new screenshot"
                                                                }
                                               };
            ((MenuItem)_screenshotsMenu[0]).Click += (sender, args) => MainWindow.SaveToFile(_img, "Select where to save the screenshot", "screenshot.png");
            ((MenuItem)_screenshotsMenu[1]).Click += (sender, args) => _screenshots.Load(_img, true);
            ((MenuItem)_screenshotsMenu[2]).Click += (sender, args) => _screenshots.Load(_img, false);

            #endregion
        }
        public MainWindow(IEnumerable<string> args)
        {
            InitializeComponent();

            this.Height = Properties.Settings.Default.Height;
            this.Width = Properties.Settings.Default.Width;
            // Very quick and dirty - but it does the job
            if(Properties.Settings.Default.Maximized) {
                WindowState = WindowState.Maximized;
                }

            foreach(var mitem in SettingsMenu.Items)
                ((MenuItem)mitem).IsEnabled = !((MenuItem)mitem).IsCheckable;
            var ver = Assembly.GetAssembly(typeof(MainWindow)).GetName().Version;
            Title = string.Format(Title, ver.Major, ver.Minor);
            Icon = App.WpfIcon;

            #region Boxart

            _boxart = new BoxartControl(this);
            BoxartTab.Content = _boxart;
            _boxartMenu = new[] {
                                    new MenuItem {
                                                     Header = "Save Cover To File"
                                                 },
                                    new MenuItem {
                                                     Header = "Select new Cover"
                                                 }
                                };
            ((MenuItem)_boxartMenu[0]).Click += _boxart.SaveImageToFileOnClick;
            ((MenuItem)_boxartMenu[1]).Click += _boxart.SelectNewCover;

            #endregion

            #region Background

            _background = new BackgroundControl(this);
            BackgroundTab.Content = _background;
            _backgroundMenu = new[] {
                                        new MenuItem {
                                                         Header = "Save Background To File"
                                                     },
                                        new MenuItem {
                                                         Header = "Select new Background"
                                                     }
                                    };
            ((MenuItem)_backgroundMenu[0]).Click += _background.SaveImageToFileOnClick;
            ((MenuItem)_backgroundMenu[1]).Click += _background.SelectNewBackground;

            #endregion

            #region Icon & Banner

            _iconBanner = new IconBannerControl(this);
            IconBannerTab.Content = _iconBanner;
            _iconBannerMenu = new UIElement[] {
                                                  new MenuItem {
                                                                   Header = "Save Icon To File"
                                                               },
                                                  new MenuItem {
                                                                   Header = "Select new Icon"
                                                               },
                                                  new Separator(),
                                                  new MenuItem {
                                                                   Header = "Save Banner To File"
                                                               },
                                                  new MenuItem {
                                                                   Header = "Select new Banner"
                                                               }
                                              };
            ((MenuItem)_iconBannerMenu[0]).Click += _iconBanner.SaveIconToFileOnClick;
            ((MenuItem)_iconBannerMenu[1]).Click += _iconBanner.SelectNewIcon;
            ((MenuItem)_iconBannerMenu[3]).Click += _iconBanner.SaveBannerToFileOnClick;
            ((MenuItem)_iconBannerMenu[4]).Click += _iconBanner.SelectNewBanner;

            #endregion

            #region Screenshots

            _screenshots = new ScreenshotsControl(this);
            ScreenshotsTab.Content = _screenshots;
            _screenshotsMenu = new[] {
                                         new MenuItem {
                                                          Header = "Save Screenshot To File"
                                                      },
                                         new MenuItem {
                                                          Header = "Replace Screenshot"
                                                      },
                                         new MenuItem {
                                                          Header = "Add new Screenshot(s)"
                                                      },
                                         new MenuItem {
                                                          Header = "Remove screenshot"
                                                      }
                                     };
            ((MenuItem)_screenshotsMenu[0]).Click += _screenshots.SaveImageToFileOnClick;
            ((MenuItem)_screenshotsMenu[1]).Click += _screenshots.SelectNewScreenshot;
            ((MenuItem)_screenshotsMenu[2]).Click += _screenshots.AddNewScreenshot;
            ((MenuItem)_screenshotsMenu[3]).Click += _screenshots.RemoveScreenshot;

            #endregion

            OnlineAssetsTab.Content = new OnlineAssetsControl(this, _boxart, _background, _iconBanner, _screenshots);
            FtpAssetsTab.Content = new FtpAssetsControl(this, _boxart, _background, _iconBanner, _screenshots);
            LocalAssetsTab.Content = new LocalAssetsControl(this, _boxart, _background, _iconBanner, _screenshots);

            var bw = new BackgroundWorker();
            bw.DoWork += (sender, e) => {
                foreach(var arg in args.Where(File.Exists)) {
                    if(VerifyAuroraMagic(arg))
                        LoadAuroraAsset(arg);
                    else
                        LoadFsdAsset(arg);
                    }
            };
            bw.RunWorkerCompleted += (sender, e) => BusyIndicator.Visibility = Visibility.Collapsed;
            if(!args.Any())
                return;
            BusyIndicator.Visibility = Visibility.Visible;
            bw.RunWorkerAsync();
        }