using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using MarketData.MarketDataModel;
using MarketData.Service;
using Navigator.Core;
using Navigator.Utils;
using Xamarin.Essentials;

namespace Navigator.ViewModels
{
    public class HeadlinesViewModel : WorkspaceViewModel 
    {
      private ObservableCollection<String> headlineDates=null;
      private ObservableCollection<Headline> headlines=null;
      private RelayCommand refreshCommand;
      private bool isRefreshing=false;
      private Headline selectedHeadline;
      private String selectedHeadlineDate;
      private bool showActivity = true;


      public HeadlinesViewModel()
      {
        Title="Headlines";
        PropertyChanged+=OnViewModelPropertyChanged;
        Initialize();
      }
      public void Initialize()
      {
        IsBusy=true;
         Task workerTask=Task.Factory.StartNew(()=>
         {
           ServiceResult serviceResult = MarketDataServiceClient.GetInstance().GetHeadlineDates();
           if (serviceResult.Success)
           {
             List<String> headlineDates = (List<String>)serviceResult.ContextSpecificResult;
             for(int index=0;index<headlineDates.Count;index++)headlineDates[index]=String.Format("{0:dddd, MMMM d, yyyy}",Utility.ParseDate(headlineDates[index]));
             if (null != headlineDates && headlineDates.Count > 0)
             {
               HeadlineDates = new ObservableCollection<string>(headlineDates);
//               SelectedHeadlineDate = headlineDates[0];
             }
           }
         });
         workerTask.ContinueWith((continuation)=>
         {
           IsBusy=false;
           SelectedHeadlineDate = headlineDates[0];
         });
      }
      private void OnViewModelPropertyChanged(object sender,PropertyChangedEventArgs eventArgs)
      {
        if(eventArgs.PropertyName.Equals("SelectedHeadline"))
        {
          HandleSelectedHeadline();
        }
        else if(eventArgs.PropertyName.Equals("SelectedHeadlineDate"))
        {
          HandleHeadlinesRefresh();
        }
      }
      private void HandleSelectedHeadline()
      {
        if(null==selectedHeadline)return;
        StringBuilder sb=new StringBuilder();
        sb.Append("https://www.google.com/search?q=").Append(Uri.EscapeDataString(selectedHeadline.Entry)).Append("/");
        Browser.OpenAsync(sb.ToString());
      }
      public void HandleHeadlinesRefresh()
      {
        IsBusy=true;
        ShowActivity=!IsRefreshing;
        Task workerTask=Task.Factory.StartNew(()=>
        {
          ServiceResult serviceResult = null;
          if(null!=selectedHeadlineDate)serviceResult=MarketDataServiceClient.GetInstance().GetHeadlines(Utility.ParseDate(selectedHeadlineDate));
          else serviceResult=MarketDataServiceClient.GetInstance().GetLatestHeadlines(); 
          if (serviceResult.Success)
          {
            List<Headline> headlines = (List<Headline>)serviceResult.ContextSpecificResult;
            Headlines=new ObservableCollection<Headline>(headlines);
          }
        });
        workerTask.ContinueWith((continuation)=>
        {
          IsBusy=false;
          IsRefreshing=false;
          ShowActivity=!IsRefreshing;
        });
      }
      public ObservableCollection<Headline> Headlines
      {
        get{return headlines;}
        set{SetProperty(ref headlines,value);}
      }
      public bool IsRefreshing
      {
        get{return isRefreshing;}
        set{SetProperty(ref isRefreshing,value);}
      }
      public Headline SelectedHeadline
      {
        get{return selectedHeadline;}
        set{SetProperty(ref selectedHeadline,value);}
      }
      public String SelectedHeadlineDate
      {
        get{return selectedHeadlineDate;}
        set{SetProperty(ref selectedHeadlineDate,value);}
      }
      public ObservableCollection<String> HeadlineDates
      {
        get{return headlineDates;}
        set{SetProperty(ref headlineDates,value);}
      }
      // If the Refreshing Indicstor is showing we don't want to show the ControlTemplate indicator... but we do want the screen to shade while the operation runs
      public bool ShowActivity
      {
        get {return showActivity;}
        set {SetProperty(ref showActivity,value);}
      }
      public ICommand RefreshCommand
      {
        get
        {
          if(null==refreshCommand)
          {
            refreshCommand=new RelayCommand(param=>
            {
              HandleHeadlinesRefresh();
 //             IsRefreshing=false;
            },param=>{return !IsRefreshing;});
          }
          return refreshCommand;
        }
      }
    }
}
