﻿using System;
using System.Net;
using System.IO;
using CoreGraphics;
using UIKit;
using Foundation;
using System.Collections.Generic;

namespace HelloXamarin
{
	public class ImageLoaderUtil
	{

		public ImageLoaderUtil()
		{
		}

		public static void showImage(UIImageView iv, String iconUrl, String iconName)
		{
			Console.WriteLine(iconUrl);
			Dictionary<String, String> dic = CacheHelper.getInstance().downloadMap;
			if (dic.ContainsKey(iconUrl))
			{
				if (dic[iconUrl] != null && !dic[iconUrl].Equals(""))
				{
					Console.WriteLine("已经下载过无需再次下载");
					String lPath = dic[iconUrl];
					Console.WriteLine(lPath);
					iv.Image = UIImage.FromFile(lPath);
					return;
				}
			}

			var webClient = new WebClient();
			webClient.DownloadDataCompleted += (s, e) =>
			{
				var bytes = e.Result;
				string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
				string localFilename = iconName;
				string localPath = Path.Combine(documentsPath, localFilename);

				Console.WriteLine("localPath:" + localPath);

				File.WriteAllBytes(localPath, bytes);

				// IMPORTANT: this is a background thread, so any interaction with
				// UI controls must be done via the MainThread
				iv.InvokeOnMainThread(() => {
					iv.Image = UIImage.FromFile(localPath);
					Dictionary<String, String> aa = CacheHelper.getInstance().downloadMap;
					if (!aa.ContainsKey(iconUrl)) {
						aa.Add(iconUrl, localPath);
					}
					//CacheHelper.getInstance().downloadMap.Add(iconUrl, localPath);
				});
			};

			var url = new Uri("http://" + iconUrl);
			webClient.DownloadDataAsync(url);
		}
	}
}
