/*
        private string GetMergeWords(int numOfWordsPerPage_, LinkedList<string> contentWords, bool isNoMoreText)
        {
            //Helper method to collect context of page

                var piece_ = new StringBuilder();
                for (int i_ = 0; i_ < numOfWordsPerPage_; i_++)
                {
                    if (contentWords.Count > 0)
                    {
                        string word_ = contentWords.First.Value;
                        piece_.Append(word_).Append(" ");
                        contentWords.RemoveFirst();
                    }
                    else
                    {
                        isNoMoreText = true;
                        break;
                    }
                }
                return piece_.ToString();
        }
        */
        private void AppendHelper(DataModel.NewsItem item, string itemGuid)
        {
            var uItem = MiscHelpers.CreateUINewsItem(item);

            var pages = new LinkedList<Page>();

            //Text-related
            var content = uItem.NewsContent;

            //ToDo: Handle when content is null
            if (content == null) return;

            //Check if context is in English or other lanaguage
            bool isOtherLanguage = content.ToCharArray().Any(c => char.GetUnicodeCategory(c) == UnicodeCategory.OtherLetter);

            int numOfWordsPerPage;
            int numOfWordsPerPage2;
            string[] words;

            //Split the words according to its language
            if (isOtherLanguage)
            {
                numOfWordsPerPage = _sizeConfig[3];
                numOfWordsPerPage2 = _sizeConfig[4];
                words = content.ToCharArray().Select(c => c.ToString()).ToArray();
            }
            else
            {
                numOfWordsPerPage = _sizeConfig[1];
                numOfWordsPerPage2 = _sizeConfig[2];
                words = content.Split(' ');
            }

            var contentWords = new LinkedList<string>(words);

            //Image-related
            var images = uItem.NewsImages;
            var numOfImages = images.Count;
            int imageTh = 0;

            bool isNoMoreText = false;
            bool isNoMoreImage = false;

            //Helper method to retrieve bitmap image
            var getBitmapImage = new Func<BitmapImage>(() =>
                {
                    BitmapImage image_ = null;
                    if (imageTh < numOfImages && images != null && images[imageTh] != null)
                    {
                        //Collect image of page
                        image_ = new BitmapImage(new Uri(images[imageTh], UriKind.Absolute));
                        image_.CreateOptions = BitmapCreateOptions.BackgroundCreation;
                        imageTh++;
                    }
                    else
                    {
                        isNoMoreImage = true;
                    }
                    return image_;
                });

            //Helper method to collect context of page
            var getMergeWords = new Func<int, string>((numOfWordsPerPage_) =>
                {
                    var piece_ = new StringBuilder();
                    for (int i_ = 0; i_ < numOfWordsPerPage_; i_++)
                    {
                        if (contentWords.Count > 0)
                        {
                            string word_ = contentWords.First.Value;
                            piece_.Append(word_).Append(" ");
                            contentWords.RemoveFirst();
                        }
                        else
                        {
                            isNoMoreText = true;
                            break;
                        }
                    }
                    return piece_.ToString();
                });

            for (int k = 0; k < 10; k++)
            {
                string text = "";
                BitmapImage image1 = getBitmapImage();
                BitmapImage image2 = null;

                if (!isNoMoreImage)
                {
                    if (!isNoMoreText)
                    {
                        text = getMergeWords(numOfWordsPerPage);
                    }
                    else
                    {
                        image2 = getBitmapImage();
                    }
                }
                else
                {
                    text = getMergeWords(numOfWordsPerPage2);
                }

                //Validate image by its dimension
                if (image1 != null && image1.PixelWidth < 100)
                {
                    image1 = null;
                    text += getMergeWords(numOfWordsPerPage2);
                }
                if (image2 != null && image2.PixelWidth < 100)
                {
                    image2 = null;
                    text += getMergeWords(numOfWordsPerPage2);
                }

                //Create page object and append it to page-list
                if (!(image1 == null && image2 == null && "".Equals(text)))
                {
                    string title = null;
                    if (_categoryName != null)
                    {
                        title = _cf[_categoryName]["title"];
                    }

                    pages.AddLast(new Page
                        {
                            Header = null,
                            SubHeader = null,
                            Content = text,
                            NewsImageSource = image1,
                            NewsImageSource2 = image2,
                            Category = title,
                            FontSize = _sizeConfig[0],
                            WebLink = uItem.NewsLink
                        });
                }
                else
                {
                    break;
                }

                if (isNoMoreText && isNoMoreImage)
                {
                    break;
                }
            }

            //var favouriteChannelItem = MiscHelpers.GetChannelItemFromIsolatedStorage("fbd-favorites.xml");
            //var readLaterChannelItem = MiscHelpers.GetChannelItemFromIsolatedStorage("fbd-readlater.xml");

            //Set header and sub-header on the 1st page
            var firstPage = pages.First.Value;
            firstPage.Header = uItem.NewsTitle;
            firstPage.FeedTitle = uItem.FeedTitle;
            firstPage.NewsPublishedDateDisplay = uItem.NewsPublishedDateDisplay;
            /*
            firstPage.ImageFavourite = _m.IsNewsItemInList(favouriteChannelItem, uItem.Tag.ToString())
                                                   ? _m.imageFavouriteOn
                                                   : _m.imageFavouriteOff;
            firstPage.ImageReadLater = _m.IsNewsItemInList(readLaterChannelItem, uItem.Tag.ToString())
                                       ? _m.imageReadLaterOn
                                       : _m.imageReadLaterOff;
            */
            firstPage.Tag = uItem.Tag;

            //Create vertical page-slider for 1 article
            var radSlideView = new RadSlideView();
            radSlideView.Orientation = System.Windows.Controls.Orientation.Vertical;
            radSlideView.TransitionMode = SlideViewTransitionMode.Flip;
            radSlideView.ItemTemplateSelector = PageTemplateSelector;
            radSlideView.ItemsSource = pages;

            //Create pivot-item, insert it to pivot (SlideView)
            var grid = new Grid { Height = 800, Margin = new Thickness(0) };
            grid.Children.Add(radSlideView);
            var pivotItem = new PivotItem { Content = grid, Margin = new Thickness(0), Tag = item };

            SlideView.Items.Add(pivotItem);

            if (itemGuid.Equals(item.Tag.ToString()))
            {
                SlideView.SelectedItem = pivotItem;

                _currentViewingItem = item;

                //Add news-item to historical view
                GeneralHelper.AddToHistoricalView(item);

                SetMarkers(_currentViewingItem);
            }
        }
        private void SlideViewSlided(object sender, SelectionChangedEventArgs e)
        {
            var pivot = sender as Pivot;
            var newsItem = pivot.SelectedItem as PivotItem;
            if (newsItem != null)
            {
                _currentViewingItem = newsItem.Tag as DataModel.NewsItem;
                //Add news-item to historical view
                GeneralHelper.AddToHistoricalView(_currentViewingItem);

                SetMarkers(_currentViewingItem);
            }
        }
        private void DownloadCompletedCallback(Object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error != null) return;
            if (string.IsNullOrEmpty(e.Result)) return;

            var root = JsonConvert.DeserializeObject<DataModel.FacebookFeeds>(e.Result);

            DataModel.ChannelItem channelItem = null;

            if (root.Data != null)
            {
                var fbfeeds = root.Data;

                var entry = fbfeeds[0];

                var newsItemList = new List<DataModel.NewsItem>();

                foreach (var f in fbfeeds)
                {
                    var title = f.Name;
                    if (f.From != null && f.From.Name != null)
                    {
                        title = f.From.Name;
                    }

                    var message = f.Message;
                    if (f.Message == null)
                    {
                        message = f.Caption;
                    }
                    if (f.Message != null && f.Caption != null && f.Caption.Length > f.Message.Length)
                    {
                        message = f.Caption;
                    }

                    var item = new DataModel.NewsItem()
                    {
                        Tag = "news|" + f.Link + "|fbfeeds",
                        NewsContent = message,
                        NewsLink = f.Link,
                        NewsSnippet = message,
                        NewsTitle = title,
                        NewsImages = new List<string>(){f.Picture},
                        FeedTitle = "Facebook",
                        FeedUrl = "fbfeeds",
                        IsNew = false
                    };
                    newsItemList.Add(item);
                }

                channelItem = new DataModel.ChannelItem()
                {
                    Tag = "feed|fbfeeds|fbfeeds",

                    NewsItems = newsItemList,

                    NewsContent = entry.Message,
                    NewsLink = entry.Link,
                    NewsSnippet = entry.Message,
                    NewsTitle = entry.Name,
                    NewsImages = new List<string>() { entry.Picture }
                };

                //var userToken = e.UserState as DataModel.UserToken;
            }
            else
            {
                //ToDO: Feed obj not available, provide url instead

                channelItem = new DataModel.ChannelItem()
                {
                    Tag = "feed|fbfeeds|fbfeeds"
                };
            }

            var u = e.UserState as DataModel.UserToken;

            if (u != null)
            {
                // Write to the Isolated Storage
                if (u.DataFetchType != null)
                {
                    MiscHelpers.SaveDataToIsolatedStorage(u.DataFetchType + ".xml", channelItem, typeof(DataModel.ChannelItem));
                    /*
                    if ((u.DataFetchType).StartsWith("fbd-"))
                    {
                        AppendFreshNewsItemToChannelStorage(new KeyValuePair<string, DataModel.ChannelItem>("fbfeeds",
                                                                                                            channelItem));
                    }
                    else
                    {
                        MiscHelpers.SaveDataToIsolatedStorage(u.DataFetchType + ".xml", channelItem, typeof(DataModel.ChannelItem));
                    }
                     */
                }

                //Reset variables
                //_newsList = new List<DataModel.ContextItem>();

                //Call ScheduledAgent's NotifyCompleted() or other callback
                if (u.Callback != null)
                {
                    (u.Callback).Invoke();
                }
            }
            else
            {
                //Web-fetch only: _feedItemlist
            }
        }