context: using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Text;
  
  using Android.App;
  using Android.Content;
  using Android.OS;
  using Android.Runtime;
  using Android.Util;
  using Android.Views;
  using Android.Widget;
  using System.Threading.Tasks;
  using Android.Support.V4.Widget;
  using Android.Support.Design.Widget;
  using Android.Support.V7.Widget;
  using System.Threading;
  using Android.Support.V7.View;
  using Toolbar = Android.Support.V7.Widget.Toolbar;
  using ProgressView = XamarinBindings.MaterialProgressBar;
  using EasyRecyclerView;
  using EasyRecyclerView.Addons;
  using NLog;
  
  namespace HappyPandaXDroid.Custom_Views
  {
      public class HPContent : FrameLayout
      {
          View ContentView;
          private static Logger logger = LogManager.GetCurrentClassLogger();
          public Custom_Views.PageSelector mpageSelector;
          EasyRecyclerView.EasyRecyclerView mRecyclerView;
          bool IsRefreshing = false;
          public string activityName;
          public int activityId;
          PageCheckListener listener;
          bool initialized = false;
  
          ProgressView.MaterialProgressBar mProgressView;
          public int count = 0, lastindex = 0;
          RefreshLayout.RefreshLayout mRefreshLayout;
          RecyclerView.LayoutManager mLayoutManager;
          FrameLayout mErrorFrame;
          ImageView mErrorImage;
          BookMarkList Bookmarks = new BookMarkList();
          TextView mErrorText;
          GalleryCardAdapter adapter;
          CountDown countDown;
          
          bool isLoading = false;
          bool IsLoading {
              get { return isLoading; }
              set
              {
                  if (value == false)
                      Task.Run(() => {
                          countDown.Start();
                                  });
                  else
                      isLoading = value;
              }
          }
          int page = 0;
          public int CurrentPage
          {
              get
              {
                  return page;
              }
              set
              {
                  page = value;
              }
          }
  
         string current_query = string.Empty;
          public String Current_Query
          {
              get
              {
                  return current_query;
              }
              set
              {
                  current_query = value;
                  SetMainLoading(true);
                  Refresh();
              }
          }
          public DialogEventListener dialogeventlistener;
          public HPContent(Context context, IAttributeSet attrs) :
              base(context, attrs)
          {
              Initialize();
          }
  
          public HPContent(Context context, IAttributeSet attrs, int defStyle) :
              base(context, attrs, defStyle)
          {
              Initialize();
          }
  
          int columns = 0;
          private void Initialize()
          {
              countDown = new CountDown(2000, 10,IsLoading);
              listener = new PageCheckListener(this);
              logger.Info("Initializing HPContent");
              ContentView = Inflate(Context, Resource.Layout.HPContent, this);
              mRecyclerView = FindViewById<EasyRecyclerView.EasyRecyclerView>(Resource.Id.recyclerView);
              adapter = new GalleryCardAdapter(this.Context);
              mRecyclerView.SetOnItemClickListener(new RecyclerViewClickListener());
              mRefreshLayout = FindViewById<RefreshLayout.RefreshLayout>(Resource.Id.refresh_layout);
              mProgressView = FindViewById<ProgressView.MaterialProgressBar>(Resource.Id.progress_view);
              mProgressView.Visibility = ViewStates.Gone;
              mErrorFrame = FindViewById<FrameLayout>(Resource.Id.error_frame);
              mErrorFrame.Visibility = ViewStates.Gone;
              mErrorImage = FindViewById<ImageView>(Resource.Id.error_image);
              mErrorImage.SetImageResource(Resource.Drawable.big_weird_face);
              mErrorText = FindViewById<TextView>(Resource.Id.error_text);
              mErrorText.Text = "Error";
              mErrorImage.Click += MErrorFrame_Click;
              SetBottomLoading(false);
              
  
              mRecyclerView.AddOnScrollListener(listener);
             
              
              if (Resources.Configuration.Orientation == Android.Content.Res.Orientation.Landscape)
                  columns = 2;
              else
                  columns = 1;
              mLayoutManager = new ExtraLayoutManager(this.Context, columns, GridLayoutManager.Vertical, false);
             
             
              mRecyclerView.SetAdapter(adapter);
              mRefreshLayout.SetOnRefreshListener(new OnRefreshListener(this));
  
              mRecyclerView.SetLayoutManager(mLayoutManager);
  
              
              SetMainLoading(true);
              mpageSelector = new Custom_Views.PageSelector();
              dialogeventlistener = new DialogEventListener(this);
              initialized = true;
              logger.Info("HPContent Initialized");
          }
  
  
  
          public class ExtraLayoutManager : GridLayoutManager
          {
              private static readonly int DEFAULT_EXTRA_LAYOUT_SPACE = 800;
              private int extraLayoutSpace = -1;
              private Context context;
  
  
              public ExtraLayoutManager(Context context,int columns) : base(context,columns)
              {
                  this.context = context;
              }
  
              public ExtraLayoutManager(Context context, int columns ,int extraLayoutSpace) : base(context,columns)
              {
                  this.context = context;
                  this.extraLayoutSpace = extraLayoutSpace;
              }
  
  
  
              public ExtraLayoutManager(Context context, int columns ,int orientation, bool reverseLayout)
                  : base(context, columns,orientation, reverseLayout)
              {
                  this.context = context;
              }
  
              public void SetExtraLayoutSpace(int extraLayoutSpace)
              {
                  this.extraLayoutSpace = extraLayoutSpace;
              }
  
              protected override int GetExtraLayoutSpace(RecyclerView.State state)
              {
                  if (extraLayoutSpace > 0)
                  {
                      return extraLayoutSpace;
                  }
                  else
                      return DEFAULT_EXTRA_LAYOUT_SPACE;
              }
          }
  
  
  
          public void OrientationChanged(Android.Content.Res.Orientation orientation)
          {
              switch (orientation)
              {
                  case Android.Content.Res.Orientation.Landscape:
                      columns = 2;
                      break;
                  default:
                      columns = 1;
                      break;
              }
              mLayoutManager = new GridLayoutManager(this.Context, columns);
              mRecyclerView.SetLayoutManager(mLayoutManager);
          }
  
          public class AutoFitGridLayout : GridLayoutManager
          {
              private int mColumnWidth;
              private bool mColumnWidthChanged = true;
  
              public AutoFitGridLayout(Context context, int columnWidth) : base(context,1)
              {
                  /* Initially set spanCount to 1, will be changed automatically later. */
                  SetColumnWidth(CheckedColumnWidth(context, columnWidth));
              }
  
              public AutoFitGridLayout(Context context, int columnWidth, int orientation, bool reverseLayout) : base (context, 1, orientation, reverseLayout)
              {
                  /* Initially set spanCount to 1, will be changed automatically later. */
  
                  SetColumnWidth(CheckedColumnWidth(context, columnWidth));
              }
  
              private int CheckedColumnWidth(Context context, int columnWidth)
              {
                  if (columnWidth <= 0)
                  {
                      /* Set default columnWidth value (48dp here). It is better to move this constant
                      to static constant on top, but we need context to convert it to dp, so can't really
                      do so. */
                      columnWidth = (int)TypedValue.ApplyDimension(ComplexUnitType.Dip, 48,
                              context.Resources.DisplayMetrics);
                  }
                  return columnWidth;
              }
  
              public void SetColumnWidth(int newColumnWidth)
              {
                  if (newColumnWidth > 0 && newColumnWidth != mColumnWidth)
                  {
                      mColumnWidth = newColumnWidth;
                      mColumnWidthChanged = true;
                  }
              }
  
              public override void OnLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state)
              {
                  int width = Width;
                  int height = Height;
                  if (mColumnWidthChanged && mColumnWidth > 0 && width > 0 && height > 0)
                  {
                      int totalSpace;
                      if (Orientation == Vertical)
                      {
                          totalSpace = width - PaddingRight - PaddingLeft;
                      }
                      else
                      {
                          totalSpace = height - PaddingTop - PaddingBottom;
                      }
                      int spanCount = Math.Max(1, totalSpace / mColumnWidth);
                      SpanCount = spanCount;
                      mColumnWidthChanged = false;
                  }
                  base.OnLayoutChildren(recycler, state);
              }
          }
  
  
          public  void InitLibrary()
          {
              int tries= 0;
              Task.Run(async () =>
               {
                   while (tries <5 && !Core.Net.Connected)
                   {
                       tries++;
                      await Task.Delay(5000);
                   }
                   if (tries >= 5 && !Core.Net.Connected)
                   {
                       {
                           var h = new Handler(Looper.MainLooper);
                           h.Post(() =>
                           {
                               SetMainLoading(false);
                               SetError(true);
                           });
                           return;
                       }
                   }
                   tries = 0;
                   if (Core.Net.Connected)
                   {
                       if (Core.Net.session_id != string.Empty && Core.Net.session_id != null)
                       {
                           {
                               logger.Info("Getting Library");
                               GetLib();
                               var h = new Handler(Looper.MainLooper);
                               h.Post(() =>
                               {
                                   SetMainLoading(false);
                                   adapter.ResetList();
                                   lastindex = Core.Gallery.CurrentList.Count - 1;
                                   SetMainLoading(false);
  
                               });
                               GetTotalCount();
                               Bookmarks.ResetList();
                               listener.AddBookmark(0);
  
                           }
                       }
                   }
                   else
                   {
                       var h = new Handler(Looper.MainLooper);
                       h.Post(() =>
                       {
                           SetMainLoading(false);
                           SetError(true);
                       });
                   }
               });
          }
  
          private void MErrorFrame_Click(object sender, EventArgs e)
          {
              SetMainLoading(true);
              Refresh();
          }
  
          private void MRefreshLayout_OnFooterRefresh(object sender, EventArgs e)
          {
  
              SetBottomLoading(true);
              ThreadStart load = new ThreadStart(NextPage);
  
gt:             Thread thread = new Thread(load);