﻿using ConTangibles.Models;
using ConTangibles.Utilities;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Storage;
using Windows.UI.Xaml.Media.Imaging;

namespace ConTangibles.Data
{
    /// <summary>
    /// Loads data.
    /// </summary>
    internal static class DataLoader
    {
        static readonly StorageFolder InstallationFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;

        /// <summary>
        /// Asynchronously loads contacts.
        /// </summary>
        /// <param name="userId">The user id.</param>
        /// <returns>a <see cref="ContactList"/>.</returns>
        public static async Task<ContactList> LoadContactsAsync(UserId userId)
        {
            var fileToRead = await InstallationFolder.GetFileAsync(GetFileName(userId));

            return await LoadContactsAsync(fileToRead);
        }

        /// <summary>
        /// Gets the file name of the given user id.
        /// </summary>
        /// <param name="userId">the user id.</param>
        /// <returns>the file name.</returns>
        static string GetFileName(UserId userId)
        {
            if (userId == UserId.User1)
                return @"Assets\Data\User1Contacts.xml";
            else if (userId == UserId.User2)
                return @"Assets\Data\User2Contacts.xml";
            else
                throw new NotSupportedException($"{userId} is not supported");
        }

        /// <summary>
        /// Asynchronously loads contacts.
        /// </summary>
        /// <param name="fileToRead">The file.</param>
        /// <returns>a <see cref="ContactList"/>.</returns>
        static async Task<ContactList> LoadContactsAsync(StorageFile fileToRead)
        {
            using (var stream = await fileToRead.OpenStreamForReadAsync())
            {
                using (StreamReader streamReader = new StreamReader(stream))
                {
                    string xml = streamReader.ReadToEnd();
                    var contactList = await Task.Run(() => { return Serializer.Deserialize<ContactList>(xml); });

                    await SetPictureUri(contactList);

                    return contactList;
                }
            }
        }

        static async Task SetPictureUri(ContactList contactList)
        {
            //return Task.Run(async () =>
            //{
            if (contactList == null)
                return;

            foreach (var contact in contactList)
            {
                if (!string.IsNullOrEmpty(contact.Picture))
                {
                    try
                    {
                        //Not working :(
                        //string fullPaths = $@"ms-appx:///ConTangibles/Assets/Data/Pictures/{contact.Picture}";
                        //Uri uri = new Uri(fullPaths);

                        var file = await InstallationFolder.GetFileAsync($@"Assets\Data\Pictures\{contact.Picture}");


                        var stream = await file.OpenAsync(FileAccessMode.Read);
                        BitmapImage image = new BitmapImage();
                        await image.SetSourceAsync(stream);



                        contact.PictureSource = image;
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex.ToString());
                    }
                }
            }

            //});


        }
    }
}
