using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using BankTV.Model;
using BankTV.Helpers.Config;
using BankTV.Exceptions;
using BankTV.Logger;
using System.IO;
using BankTV.Consts;
using BankTV.Helpers.Weather;
using BankTV.Model.Weather;
using BankTV.Helpers.Currency;
using BankTV.Model.Currency;
using System.Globalization;
using BankTV.Helpers.Config.Local;
using BankTV.Helpers.BottomBarNews;
using BankTV.Helpers.Update;
using HTMLConverter;
using System.Xml;
using System.Windows.Markup;
using BankTV.Helpers;
using System.Windows.Interop;
using BankTV.Properties;

namespace BankTV
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private int currentMedia = -1;
        private DateTime? imageShown = null;
        private DateTime? breakShown = null;
        private Timer timer = null;
        private List<Screen> playlist = null;
        private Boolean breakNow = true;
        private GlobalEnums.ScreenShownType? screenShownType = null;
        private UpdateState updateState = new UpdateState();
        private string param = String.Empty;

        private int appRefreshIntervalMinutes = GlobalConsts.APP_REFRESH_INTERVAL_MINUTES;
        private int currencyRefreshIntervalMinutes = GlobalConsts.APP_REFRESH_INTERVAL_CURRENCIES;

        public MainWindow()
        {
            InitializeComponent();
        }

        public void StartApp(string param)
        {
            this.currencyRefreshIntervalMinutes = this.getCurrencyRefreshInterval();
            this.appRefreshIntervalMinutes = this.getAppRefreshInterval();
            this.param = param;
            if (!this.initApp(this.param))
            {
                return;
            }   //if
            try
            {
                this.player.MediaEnded += player_MediaEnded;
                this.player.MediaFailed += player_MediaFailed;
                this.player.Source = null;
                this.timer = new Timer(16);
                this.timer.Elapsed += timer_Elapsed;
                this.timer.Start();
                this.PlayNext();
            }   //try
            catch (AppNotInitiatedException ex)
            {
                MessageBox.Show(ex.Message, "Ostrzeżenie", MessageBoxButton.OK, MessageBoxImage.Warning);
            }   //catch
            catch (Exception ex)
            {
                MyLogger.Log(ex);
                MessageBox.Show("Przepraszamy - wystąpił błąd w trakcie odtwarzania.", "Błąd", MessageBoxButton.OK, MessageBoxImage.Error);
            }   //catch
        }

        private void PlayNext()
        {
            if ((!this.updateState.appUpdated.HasValue)
                || ((DateTime.Now - this.updateState.appUpdated.Value).TotalMinutes > this.appRefreshIntervalMinutes))
            {
                if (!this.initApp(this.param))
                {
                    return;
                }   //if
                this.updateState.currencyUpdated = DateTime.Now;
            }   //if
            if ((!this.updateState.currencyUpdated.HasValue)
                || ((DateTime.Now - this.updateState.currencyUpdated.Value).TotalMinutes > this.currencyRefreshIntervalMinutes))
            {
                this.initCurrency();
                this.updateState.currencyUpdated = DateTime.Now;
            }   //if
            this.newsContent.Opacity = 0;
            this.weatherContent.Opacity = 0;
            this.currencyContent.Opacity = 0;
            this.newsContent.Visibility = Visibility.Visible;
            this.weatherContent.Visibility = Visibility.Visible;
            this.currencyContent.Visibility = Visibility.Visible;
            if (this.playlist.Count == 0)
            {
                throw new AppNotInitiatedException("Lista ekranów jest pusta. Proszę uruchomić aktualizator oraz upewnić się, że dane na serwerze zostały poprawnie skonfigurowane.");
            }   //if
            try
            {
                this.currentMedia++;
                if (this.currentMedia >= this.playlist.Count)
                {
                    this.currentMedia = 0;
                }   //if
                Screen screen = playlist[currentMedia];
                if (screen == null)
                {
                    return;
                }   //if
                switch (screen.Type)
                {
                    case Screen.ScreenType.IMG:
                        this.screenShownType = GlobalEnums.ScreenShownType.IMG;
                        this.ShowImage(screen.GetFilePath());
                        break;
                    case Screen.ScreenType.MV:
                        this.screenShownType = GlobalEnums.ScreenShownType.MV;
                        this.ShowVideo(screen.GetFilePath());
                        break;
                    case Screen.ScreenType.SWF:
                        this.screenShownType = GlobalEnums.ScreenShownType.SWF;
                        this.ShowFlash(screen.GetFilePath());
                        break;
                    case Screen.ScreenType.NEWS:
                        this.screenShownType = GlobalEnums.ScreenShownType.NEWS;
                        this.ShowNews(screen);
                        break;
                    case Screen.ScreenType.PD:
                        this.ShowPredefinedScreen(screen);
                        break;
                    default:
                        this.screenShownType = GlobalEnums.ScreenShownType.IMG;
                        this.ShowDefaultImage();
                        break;
                }   //switch
            }   //try
            catch (Exception ex)
            {
                MyLogger.Log(ex);
            }   //catch
        }

        private void ShowBreak() {
            this.breakShown = DateTime.Now;
            this.breakNow = false;
            Storyboard stbImagefadeOut = (Storyboard)FindResource("imageFadeOut");
            stbImagefadeOut.Begin();
        }

        private void ShowNewsBreak()
        {
            this.breakShown = DateTime.Now;
            this.breakNow = false;
            Storyboard stbFadeOut = (Storyboard)FindResource("newsFadeOut");
            stbFadeOut.Begin();
        }

        private void ShowCurrencyBreak()
        {
            this.breakShown = DateTime.Now;
            this.breakNow = false;
            Storyboard stbFadeOut = (Storyboard)FindResource("currencyFadeOut");
            stbFadeOut.Begin();
        }

        private void ShowWeatherBreak()
        {
            this.breakShown = DateTime.Now;
            this.breakNow = false;
            Storyboard stbFadeOut = (Storyboard)FindResource("weatherFadeOut");
            stbFadeOut.Begin();
        }

        private void ShowFlashBreak()
        {
            this.breakShown = DateTime.Now;
            this.breakNow = false;
            Storyboard stbFadeOut = (Storyboard)FindResource("flashFadeOut");
            flashContent.StopMovie();
            stbFadeOut.Begin();
        }

        void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            Dispatcher.BeginInvoke(new Action(() =>
            {
                if (this.breakNow) {
                    if (imageShown.HasValue) {
                        if ((DateTime.Now - imageShown.Value).TotalSeconds > 20) 
                        {                        
                            this.breakShown = null;
                            if (!this.screenShownType.HasValue)
                            {
                                this.ShowBreak();
                            }   //if                 
                            else
                            {
                                switch (this.screenShownType)
                                {
                                    case GlobalEnums.ScreenShownType.CURRENCY:
                                        this.ShowCurrencyBreak();
                                        break;
                                    case GlobalEnums.ScreenShownType.IMG:
                                        this.ShowBreak();
                                        break;
                                    case GlobalEnums.ScreenShownType.MV:
                                        this.ShowBreak();
                                        break;
                                    case GlobalEnums.ScreenShownType.SWF:
                                        this.ShowFlashBreak();
                                        break;
                                    case GlobalEnums.ScreenShownType.NEWS:
                                        this.ShowNewsBreak();
                                        break;
                                    case GlobalEnums.ScreenShownType.UNKNOWN:
                                        this.ShowBreak();
                                        break;
                                    case GlobalEnums.ScreenShownType.WEATHER:
                                        this.ShowWeatherBreak();
                                        this.updateWeatherIfNeeded();
                                        this.initWeather();
                                        break;
                                    default:
                                        this.ShowBreak();
                                        break;
                                }   //switch
                            }   //else
                        }
                    }
                }
                else {
                    if (breakShown.HasValue) {
                        if ((DateTime.Now - breakShown.Value).TotalSeconds > 2)
                        {
                            //return;
                            this.imageShown = null;
                            this.PlayNext();
                        }
                    }
                }
                bottomBar.Update();
            }));
        }

        void image_Loaded(object sender, RoutedEventArgs e)
        {

        }

        private void playerFadeInCompleted(object sender, EventArgs e)
        {
            //this.player.Play();
        }

        void player_MediaEnded(object sender, RoutedEventArgs e)
        {
            Storyboard stbPlayerfadeOut = (Storyboard)FindResource("playerFadeOut");
            stbPlayerfadeOut.Begin();
            this.breakShown = DateTime.Now;
            breakNow = false;
            this.player.Source = null;
        }

        void player_MediaFailed(object sender, ExceptionRoutedEventArgs  e)
        {
            try
            {
                if (e != null)
                {
                    if (e.ErrorException != null)
                    {
                        MyLogger.Log(e.ErrorException);
                        MyLogger.Log(e.ErrorException.GetBaseException());
                    }   //if
                }   //if
            }   //try
            catch (Exception ex)
            {
                MyLogger.Log(ex);
            }   //catch
            this.player.Source = null;
            this.imageShown = null;
            this.PlayNext();            
        }
        
        private void ShowImage(string filePath)
        {            
            if (String.IsNullOrEmpty(filePath))
            {
                this.ShowDefaultImage();
                return;
            }   //if
            if (!File.Exists(filePath))
            {
                this.ShowDefaultImage();
                return;
            }   //if
            this.imageShown = DateTime.Now;
            this.image.SetValue(Image.SourceProperty, new ImageSourceConverter().ConvertFromString(new Uri(filePath, UriKind.Absolute).ToString()));
            Storyboard stbImageFadeIn = (Storyboard)FindResource("imageFadeIn");
            stbImageFadeIn.Begin();
            this.breakNow = true;
        }

        private void ShowVideo(string filePath)
        {
            if (String.IsNullOrEmpty(filePath))
            {
                this.ShowDefaultImage();
                return;
            }   //if
            if (!File.Exists(filePath))
            {
                this.ShowDefaultImage();
                return;
            }   //if            
            this.player.Source = new Uri(filePath, UriKind.Absolute);
            //this.player.Pause();
            Storyboard stbPlayerFadeIn = (Storyboard)FindResource("playerFadeIn");
            stbPlayerFadeIn.Begin();
            this.breakNow = true;
        }

        private void ShowFlash(string filePath)
        {
            if (String.IsNullOrEmpty(filePath))
            {
                this.ShowDefaultImage();
                return;
            }   //if
            if (!File.Exists(filePath))
            {
                this.ShowDefaultImage();
                return;
            }   //if
            this.imageShown = DateTime.Now;
            flashContent.Visibility = Visibility.Visible;
            flashContent.Source = new Uri(filePath, UriKind.Absolute);
            flashContent.PlayMovie();
            Storyboard stbFlashFadeIn = (Storyboard)FindResource("flashFadeIn");
            stbFlashFadeIn.Begin();
            this.breakNow = true;
        }

        private void ShowWaluty()
        {
            if (!this.updateState.currencyInited)
            {
                List<CurrencyItem> currencyItems = CurrencyHelper.GetCurrencyItems();
                this.initCurrency(currencyItems);
            }   //if
            this.imageShown = DateTime.Now;
            Storyboard stbFadeIn = (Storyboard)FindResource("currencyFadeIn");
            stbFadeIn.Begin();
            this.breakNow = true;
            //this.currencyContent.Visibility = Visibility.Visible;
        }

        private void ShowPogoda()
        {
            if (!this.updateState.weatherInited)
            {
                this.initWeather();
            }   //if
            this.imageShown = DateTime.Now;
            Storyboard stbFadeIn = (Storyboard)FindResource("weatherFadeIn");
            stbFadeIn.Begin();
            this.breakNow = true;
            //this.weatherContent.Visibility = Visibility.Visible;
        }

        private void ShowDefaultImage()
        {
            this.ShowStaticImage("logo.png");
        }

        private void ShowNews(Screen screen)
        {
            if (screen == null)
            {
                this.ShowDefaultImage();
                return;
            }   //if
            if (String.IsNullOrEmpty(screen.Title))
            {
                screen.Title = String.Empty;
            }   //if
            this.newsContent.lblNewsTitle.Content = screen.Title.ToUpper();
            string xamlString = this.UpdateNewsHtmlContent(screen.Content);
            if (xamlString == null)
            {
                this.ShowDefaultImage();
                return;
            }   //if
            try
            {
                StringReader stringReader = new StringReader(xamlString);
                XmlReader xmlReader = System.Xml.XmlReader.Create(stringReader);
                Section sec = XamlReader.Load(xmlReader) as Section;
                FlowDocument flowDocument = new FlowDocument();
                flowDocument.FontSize = 28;
                flowDocument.FontFamily = new FontFamily("/BankTV;component/Fonts/OpenSans/#Open Sans");                
                while (sec.Blocks.Count > 0)
                {
                    flowDocument.Blocks.Add(sec.Blocks.FirstBlock);
                }   //while
                newsContent.tbNewsContent.Document = flowDocument;
            }   //try
            catch (Exception ex)
            {
                MyLogger.Log(ex);
                this.ShowDefaultImage();
                return;
            }   //catch
            string filePath = screen.GetFilePath();
            if ((!String.IsNullOrEmpty(filePath)) && (File.Exists(filePath)))
            {
                this.newsContent.imgNews.SetValue(Image.SourceProperty, new ImageSourceConverter().ConvertFromString(new Uri(filePath, UriKind.Absolute).ToString()));
            }   //if            
            else
            {
                this.newsContent.imgNews.SetValue(Image.SourceProperty, new ImageSourceConverter().ConvertFromString(new Uri("pack://application:,,,/BankTV;component/Images/logo.png").ToString()));
            }
            this.imageShown = DateTime.Now;
            Storyboard stbFadeIn = (Storyboard)FindResource("newsFadeIn");
            stbFadeIn.Begin();
            this.breakNow = true;
            //this.newsContent.Visibility = Visibility.Visible;
        }

        private string UpdateNewsHtmlContent(string content) 
        {
            if (String.IsNullOrWhiteSpace(content))
            {
                content = String.Empty;
            }   //if
            content = content.Replace("&oacute;", "ó");
            return HtmlToXamlConverter.ConvertHtmlToXaml(content, false);
        }

        private void ShowStaticImage(string imageName)
        {
            this.imageShown = DateTime.Now;                        
            this.image.SetValue(Image.SourceProperty, new ImageSourceConverter().ConvertFromString(new Uri("pack://application:,,,/BankTV;component/Images/logo.png").ToString()));
            Storyboard stbImageFadeIn = (Storyboard)FindResource("imageFadeIn");
            stbImageFadeIn.Begin();
            this.breakNow = true;
        }

        private void ShowPredefinedScreen(Screen screen)
        {
            if (screen == null)
            {
                this.ShowDefaultImage();
                return;
            }   //if
            if (String.IsNullOrEmpty(screen.Abbr))
            {
                this.screenShownType = GlobalEnums.ScreenShownType.IMG;
                this.ShowDefaultImage();
                return;
            }   //if
            if (screen.Abbr == GlobalConsts.PD_POGODA_ABBR)
            {
                if (this.updateState.weatherErrorOccurred)
                {
                    this.ShowDefaultImage();
                    return;
                }   //if
                this.screenShownType = GlobalEnums.ScreenShownType.WEATHER;
                this.ShowPogoda();
                return;
            }   //if
            if (screen.Abbr == GlobalConsts.PD_WALUTY_ABBR)
            {
                if (this.updateState.currencyErrorOccurred)
                {
                    this.ShowDefaultImage();
                    return;
                }   //if
                this.screenShownType = GlobalEnums.ScreenShownType.CURRENCY;
                this.ShowWaluty();
                return;
            }   //if
        }

        private void initWeather()
        {
            try
            {
                if (this.updateState.weatherInited)
                {
                    return;
                }   //if
                string city = String.Empty;
                try
                {
                    city = XmlLocalConfigHelper.GetCurrentCity(this.param);
                    if (String.IsNullOrWhiteSpace(city))
                    {
                        city = GlobalConsts.CITY;
                    }   //if
                }   //try
                catch (Exception ex)
                {
                    MyLogger.Log(ex);
                    city = GlobalConsts.CITY;
                }   //catch
                try
                {
                    WeatherCurrent currentWeather = WeatherCurrentReader.GetCurrentWeather(city);
                    WeatherCurrent bialystokWeather = WeatherCurrentReader.GetWeatherBialystok();
                    WeatherCurrent szczecinWeather = WeatherCurrentReader.GetWeatherSzczecin();
                    WeatherCurrent gdanskWeather = WeatherCurrentReader.GetWeatherGdansk();
                    WeatherCurrent poznanWeather = WeatherCurrentReader.GetWeatherPoznan();
                    WeatherCurrent rzeszowWeather = WeatherCurrentReader.GetWeatherRzeszow();
                    WeatherCurrent wroclawWeather = WeatherCurrentReader.GetWeatherWroclaw();
                    WeatherCurrent warszawaWeather = WeatherCurrentReader.GetWeatherWarszawa();
                    List<WeatherForecast> forecasts = WeatherForecastReader.GetForecastWeather(city);
                    if ((currentWeather == null) || (forecasts == null))
                    {
                        this.hideUnnecessaryWeatherItems();
                        this.updateState.weatherInited = true;
                        this.updateState.weatherErrorOccurred = true;
                        return;
                    }   //if
                    if ((bialystokWeather == null) || (szczecinWeather == null) || (gdanskWeather == null) || (poznanWeather == null)
                        || (rzeszowWeather == null) || (wroclawWeather == null) || (warszawaWeather == null))
                    {
                        this.hideUnnecessaryWeatherItems();
                        this.updateState.weatherInited = true;
                        this.updateState.weatherErrorOccurred = true;
                        return;
                    }   //if
                    this.topBar.updateWeather(currentWeather, city);
                    weatherContent.lblWeatherCisnienie.Content = currentWeather.Pressure.ToString() + " hpa";
                    weatherContent.lblCurrentDay.Content = GlobalHelper.getPolishDayOfWeek(DateTime.Now);
                    weatherContent.lblWeatherCity.Content = city;
                    weatherContent.lblWeatherDate.Content = currentWeather.LastUpdate.ToString("dd.MM.yy");
                    weatherContent.lblWeatherLastUpdate.Content = currentWeather.LastUpdate.ToString("dd.MM.yy HH:mm");
                    weatherContent.lblWeatherSunrise.Content = currentWeather.SunRise.ToString("HH:mm");
                    weatherContent.lblWeatherSunset.Content = currentWeather.SunSet.ToString("HH:mm");
                    weatherContent.lblWeatherTemperature.Content = String.Format("{0}°C", currentWeather.TempAvg.ToString("0"));
                    weatherContent.lblWeatherTemperatureBialystok.Content = String.Format("{0}°C", bialystokWeather.TempMax.ToString("0"));
                    weatherContent.lblWeatherTemperatureGdansk.Content = String.Format("{0}°C", gdanskWeather.TempMax.ToString("0"));
                    weatherContent.lblWeatherTemperaturePoznan.Content = String.Format("{0}°C", poznanWeather.TempMax.ToString("0"));
                    weatherContent.lblWeatherTemperatureRzeszow.Content = String.Format("{0}°C", rzeszowWeather.TempMax.ToString("0"));
                    weatherContent.lblWeatherTemperatureSzczecin.Content = String.Format("{0}°C", szczecinWeather.TempMax.ToString("0"));
                    weatherContent.lblWeatherTemperatureWarszawa.Content = String.Format("{0}°C", warszawaWeather.TempMax.ToString("0"));
                    weatherContent.lblWeatherTemperatureWroclaw.Content = String.Format("{0}°C", wroclawWeather.TempMax.ToString("0"));
                    weatherContent.imgWeatherCurrent.SetValue(Image.SourceProperty, new ImageSourceConverter().ConvertFromString(new Uri(currentWeather.GetImagePath(), UriKind.Absolute).ToString()));
                    weatherContent.imgWeatherBialystok.SetValue(Image.SourceProperty, new ImageSourceConverter().ConvertFromString(new Uri(bialystokWeather.GetImagePath(), UriKind.Absolute).ToString()));
                    weatherContent.imgWeatherGdansk.SetValue(Image.SourceProperty, new ImageSourceConverter().ConvertFromString(new Uri(gdanskWeather.GetImagePath(), UriKind.Absolute).ToString()));
                    weatherContent.imgWeatherPoznan.SetValue(Image.SourceProperty, new ImageSourceConverter().ConvertFromString(new Uri(poznanWeather.GetImagePath(), UriKind.Absolute).ToString()));
                    weatherContent.imgWeatherRzeszow.SetValue(Image.SourceProperty, new ImageSourceConverter().ConvertFromString(new Uri(rzeszowWeather.GetImagePath(), UriKind.Absolute).ToString()));
                    weatherContent.imgWeatherSzczecin.SetValue(Image.SourceProperty, new ImageSourceConverter().ConvertFromString(new Uri(szczecinWeather.GetImagePath(), UriKind.Absolute).ToString()));
                    weatherContent.imgWeatherWarszawa.SetValue(Image.SourceProperty, new ImageSourceConverter().ConvertFromString(new Uri(warszawaWeather.GetImagePath(), UriKind.Absolute).ToString()));
                    weatherContent.imgWeatherWroclaw.SetValue(Image.SourceProperty, new ImageSourceConverter().ConvertFromString(new Uri(wroclawWeather.GetImagePath(), UriKind.Absolute).ToString()));
                    foreach (WeatherForecast forecast in forecasts)
                    {
                        if (forecast.Day.Date == DateTime.Now.AddDays(1).Date)
                        {
                            weatherContent.lblWeatherNextDayTemperature.Content = String.Format("{0}°C", forecast.TempDay.ToString("0"));
                            weatherContent.imgWeatherNextDay.SetValue(Image.SourceProperty, new ImageSourceConverter().ConvertFromString(new Uri(forecast.GetImagePath(), UriKind.Absolute).ToString()));
                            weatherContent.lblWeatherNextDayDate.Content = DateTime.Now.AddDays(1).ToString("dd.MM.yy");
                            weatherContent.lblWeatherNextDay.Content = GlobalHelper.getPolishDayOfWeek(DateTime.Now.AddDays(1));
                        }   //if
                        else if (forecast.Day.Date == DateTime.Now.AddDays(2).Date)
                        {
                            weatherContent.lblWeatherDayAfterNextTemperature.Content = String.Format("{0}°C", forecast.TempDay.ToString("0"));
                            weatherContent.imgWeatherDayAfterNext.SetValue(Image.SourceProperty, new ImageSourceConverter().ConvertFromString(new Uri(forecast.GetImagePath(), UriKind.Absolute).ToString()));
                            weatherContent.lblWeatherDayAfterNextDate.Content = DateTime.Now.AddDays(2).ToString("dd.MM.yy");
                            weatherContent.lblWeatherDayAfterNextDay.Content = GlobalHelper.getPolishDayOfWeek(DateTime.Now.AddDays(2));
                        }   //if
                        else if (forecast.Day.Date == DateTime.Now.AddDays(3).Date)
                        {
                            weatherContent.lblWeatherNextDayAfterNextTemperature.Content = String.Format("{0}°C", forecast.TempDay.ToString("0"));
                            weatherContent.imgWeatherNextDayAfterNext.SetValue(Image.SourceProperty, new ImageSourceConverter().ConvertFromString(new Uri(forecast.GetImagePath(), UriKind.Absolute).ToString()));
                            weatherContent.lblWeatherNextDayAfterNextDate.Content = DateTime.Now.AddDays(3).ToString("dd.MM.yy");
                            weatherContent.lblWeatherNextDayAfterNextDay.Content = GlobalHelper.getPolishDayOfWeek(DateTime.Now.AddDays(3));
                        }   //if
                    }   //for
                    this.updateState.weatherInited = true;
                    this.updateState.weatherErrorOccurred = false;
                }   //try
                catch (Exception ex)
                {
                    this.updateState.weatherErrorOccurred = true;
                    this.hideUnnecessaryWeatherItems();
                    MyLogger.Log(ex);
                }   //catch
            }
            catch (Exception ex)
            {
                this.updateState.weatherErrorOccurred = true;
                this.hideUnnecessaryWeatherItems();
                MyLogger.Log(ex);
            }
        }

        private void updateCurrencyItem(CurrencyItem item, Label sellingPrice, Label buiyingPrice)
        {
            if (item == null)
            {
                return;
            }
            if (sellingPrice == null)
            {
                return;
            }
            if (buiyingPrice == null)
            {
                return;
            }
            sellingPrice.Content = item.SellingPrice.ToString("0.0000", CultureInfo.InvariantCulture);
            buiyingPrice.Content = item.BuyingPrice.ToString("0.0000", CultureInfo.InvariantCulture);
        }

        private void initCurrency(List<CurrencyItem> currencyItems)
        {
            if (currencyItems == null)
            {
                return;
            }   //if
            foreach (CurrencyItem item in currencyItems)
            {
                if (item.Abbr.Equals("USD"))
                {
                    this.updateCurrencyItem(item, currencyContent.lblUSDSellingPrice, currencyContent.lblUSDBuyingPrice);
                }   //if
                else if (item.Abbr.Equals("EUR"))
                {
                    this.updateCurrencyItem(item, currencyContent.lblEURSellingPrice, currencyContent.lblEURBuyingPrice);
                }   //if
                else if (item.Abbr.Equals("GBP"))
                {
                    this.updateCurrencyItem(item, currencyContent.lblGBPSellingPrice, currencyContent.lblGBPBuyingPrice);
                }   //if
            }   //for
            this.updateState.currencyInited = true;
        }

        private void initCurrency()
        {
            List<CurrencyItem> currencyItems = CurrencyHelper.GetCurrencyItems();
            if (currencyItems == null)
            {
                this.updateState.currencyErrorOccurred = true;
                return;
            }   //if
            try
            {
                this.initCurrency(currencyItems);
                this.bottomBar.UpdateCurrencyValues(currencyItems);
                this.updateState.currencyInited = true;
                this.updateState.currencyErrorOccurred = false;
            }   //try
            catch (Exception ex)
            {
                MyLogger.Log(ex);
                this.updateState.currencyErrorOccurred = true;
            }   //catch
        }

        private void initBottomBarNews()
        {
            List<string> bottomBarNews = BottomBarNewsXmlHelper.GetBottomBarNewsValues();
            if (bottomBarNews == null)
            {
                bottomBarNews = new List<string>();
            }   //if
            try
            {
                this.bottomBar.UpdateNewsBar(bottomBarNews);
            }   //try
            catch (Exception ex)
            {
                MyLogger.Log(ex);
            }   //catch
        }

        private void updateWeatherIfNeeded()
        {
            try
            {
                if (!this.updateState.weatherUpdated.HasValue)
                {
                    string city = String.Empty;
                    try
                    {
                        city = XmlLocalConfigHelper.GetCurrentCity(this.param);
                        if (String.IsNullOrWhiteSpace(city))
                        {
                            city = GlobalConsts.CITY;
                        }   //if
                    }   //try
                    catch (Exception ex)
                    {
                        MyLogger.Log(ex);
                        city = GlobalConsts.CITY;
                    }   //catch
                    if (!WeatherApiHelper.UpdateWeather(city))
                    {                        
                        throw new Exception("Unable to update weather data...");
                    }   //if
                    return;
                }   //if
                if (((DateTime.Now - this.updateState.weatherUpdated.Value).TotalHours > GlobalConsts.WEATHER_REFRESH_INTERVAL)
                    || (((DateTime.Now - this.updateState.weatherUpdated.Value).TotalMinutes > GlobalConsts.WEATHER_ERROR_REFRESH_MINUTES_INTERVAL) && (this.updateState.weatherErrorOccurred)))
                {
                    string city = String.Empty;
                    try
                    {
                        city = XmlLocalConfigHelper.GetCurrentCity(this.param);
                        if (String.IsNullOrWhiteSpace(city))
                        {
                            city = GlobalConsts.CITY;
                        }   //if
                    }   //try
                    catch (Exception ex)
                    {
                        MyLogger.Log(ex);
                        city = GlobalConsts.CITY;
                    }   //catch
                    if (!WeatherApiHelper.UpdateWeather(city))
                    {
                        throw new Exception("Unable to update weather data...");
                    }   //if
                    this.updateState.weatherInited = false;
                    return;
                }   //if
            }
            catch (Exception ex)
            {
                this.updateState.weatherErrorOccurred = true;
                this.updateState.weatherUpdated = DateTime.Now;
                MyLogger.Log(ex);
            }
        }

        private void hideUnnecessaryWeatherItems()
        {
            this.topBar.hideUnnecessaryWeatherItems();
        }

        private bool initApp(String param)
        {
            try
            {
                if (String.IsNullOrWhiteSpace(param))
                {
                    this.playlist = XmlConfigHelper.GetScreensList();
                }
                else
                {
                    String fileName = String.Format("{0}-{1}{2}", GlobalConsts.APP_CONFIG_FILE_PREFIX, param, GlobalConsts.APP_CONFIG_FILE_SUFFIX);
                    this.playlist = XmlConfigHelper.GetScreensList(fileName);
                }
            }   //try
            catch (AppNotInitiatedException)
            {
                MessageBox.Show("Lista ekranów jest pusta. Proszę uruchomić aktualizator oraz upewnić się, że dane na serwerze zostały poprawnie skonfigurowane.", "Ostrzeżenie", MessageBoxButton.OK, MessageBoxImage.Warning);
                return false;
            }   //catch
            try
            {
                this.topBar.Update();
                this.updateWeatherIfNeeded();                
                this.initCurrency();
                this.initBottomBarNews();
                this.initWeather();
                this.updateState.appUpdated = DateTime.Now;
                return true;
            }   //try
            catch (AppNotInitiatedException ex)
            {
                MessageBox.Show(ex.Message, "Ostrzeżenie", MessageBoxButton.OK, MessageBoxImage.Warning);
                return false;
            }   //catch
            catch (Exception ex)
            {
                MyLogger.Log(ex);
                MessageBox.Show("Przepraszamy - wystąpił błąd w trakcie odtwarzania.", "Błąd", MessageBoxButton.OK, MessageBoxImage.Error);
                return false;
            }   //catch
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                var hwndSource = PresentationSource.FromVisual(this) as HwndSource;
                if (hwndSource != null)
                {
                    var hwndTarget = hwndSource.CompositionTarget;
                    if (hwndTarget != null) hwndTarget.RenderMode = RenderMode.SoftwareOnly;
                }   //if
            }   //try
            catch (Exception ex)
            {
                MyLogger.Log(ex);
                MessageBox.Show("Przepraszamy - wystąpił błąd w trakcie uruchamiania aplikacji.", "Błąd", MessageBoxButton.OK, MessageBoxImage.Error);
            }   //catch
        }

        private int getCurrencyRefreshInterval()
        {
            int? value = GlobalHelper.GetIntValueFromAppConfig(GlobalConsts.APP_REFRESH_INTERVAL_CURRENCIES_KEY);
            if (value.HasValue)
            {
                if (value.Value > 0)
                {
                    return value.Value;
                }   //if
            }   //if
            return GlobalConsts.APP_REFRESH_INTERVAL_CURRENCIES;
        }

        private int getAppRefreshInterval()
        {
            int? value = GlobalHelper.GetIntValueFromAppConfig(GlobalConsts.APP_REFRESH_INTERVAL_MINUTES_KEY);
            if (value.HasValue)
            {
                if (value.Value > 0)
                {
                    return value.Value;
                }   //if
            }   //if
            return GlobalConsts.APP_REFRESH_INTERVAL_MINUTES;
        }

    }
}
