// Decompiled with JetBrains decompiler
// Type: FiestaLauncher.Services.ExternalFileService
// Assembly: FiestaOnline, Version=2019.5.22.0, Culture=neutral, PublicKeyToken=null
// MVID: 2FD5EB61-BC25-469D-997E-88998E849F6A
// Assembly location: C:\Users\marbo\Documents\Gamigo 2020 Client\FiestaOnline.exe

using FiestaLauncher.gClasses;
using System;
using System.IO;
using System.Net;
using System.Security.Cryptography;

namespace FiestaLauncher.Services
{
  internal static class ExternalFileService
  {
    internal static void FileCheck()
    {
      foreach (ExternalFile external in gFiestaLauncher.Settings.Externals)
      {
        if (!(external.Hash == ExternalFileService.GetHash(external.Name)))
        {
          gFiestaLauncher.SplashWindow.RunOnUiThread((Splash.RunOnUiThreadDelegate) (() => gFiestaLauncher.SplashWindow.ShowUpdateUi()));
          ExternalFileService.UpdateFile(external.Name, external.Src);
        }
      }
      gFiestaLauncher.SplashWindow.RunOnUiThread((Splash.RunOnUiThreadDelegate) (() => gFiestaLauncher.SplashWindow.UpdateComplete()));
    }

    private static string GetHash(string file)
    {
      if (!System.IO.File.Exists(file))
        return "missing-file";
      string lower;
      using (MD5 md5 = MD5.Create())
      {
        using (FileStream fileStream = System.IO.File.OpenRead(file))
          lower = BitConverter.ToString(md5.ComputeHash((Stream) fileStream)).Replace("-", "").ToLower();
      }
      return lower;
    }

    private static void UpdateFile(string file, string url)
    {
      try
      {
        if (file.Contains("\\") && !Directory.Exists(Path.GetDirectoryName(file)))
          Directory.CreateDirectory(Path.GetDirectoryName(file));
        new WebClient().DownloadFile(url, file);
      }
      catch (Exception ex)
      {
        gFiestaLauncher.onCrash(ex);
      }
    }
  }
}
