﻿namespace Shaftware.Mojito
{
    using System;
    using System.Linq;
    using Microsoft.Phone.Shell;
    using System.Windows.Media;

    public static class AppLiveTile
    {
        public static void Update(AccountData[] accountData)
        {
            if (accountData == null)
            {
                return;
            }

            var netWorth = accountData.Sum(data => data.Balance);
            var balanceIssueCount = accountData.Count(data => data.AccountType == "bank" && data.Balance < 0);
            var loginIssueCount = accountData.Count(data => data.LoginStatus == AccountLoginStatus.Invalid);

            var tile = ShellTile.ActiveTiles.First();

            var tileData = new StandardTileData();

            tileData.Count = loginIssueCount + balanceIssueCount;
            tileData.BackTitle = "Net Worth";
            tileData.BackContent = String.Format("{0:c}", netWorth);
            if (balanceIssueCount > 0)
            {
                tileData.BackgroundImage = new Uri("/Assets/Tiles/TileMediumIconRed.png", UriKind.Relative);
                tileData.BackBackgroundImage = new Uri("/Assets/Tiles/TileMediumRed.png", UriKind.Relative);
            }
            else
            {
                tileData.BackgroundImage = new Uri("/Assets/Tiles/TileMediumIcon.png", UriKind.Relative);
                tileData.BackBackgroundImage = new Uri(String.Empty, UriKind.Relative);
            }

            tile.Update(tileData);
        }

        public static void Clear()
        {
            ShellTile.ActiveTiles.First().Update(new StandardTileData
            {
                BackTitle = String.Empty, 
                BackContent = String.Empty,
                BackgroundImage = new Uri("/Assets/Tiles/TileMediumIcon.png", UriKind.Relative),
                BackBackgroundImage = new Uri(String.Empty, UriKind.Relative),
            });
        }
    }
}
