package net.squanchy.tweets;

import android.content.Context;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.twitter.sdk.android.core.Callback;
import com.twitter.sdk.android.core.Result;
import com.twitter.sdk.android.core.TwitterException;
import com.twitter.sdk.android.core.models.Tweet;
import com.twitter.sdk.android.tweetui.SearchTimeline;
import com.twitter.sdk.android.tweetui.TimelineResult;

import net.squanchy.R;
import net.squanchy.support.view.Visibility;
import net.squanchy.tweets.view.ScrollListener;
import net.squanchy.tweets.view.TweetsAdapter;

import timber.log.Timber;

public class TweetsPageView extends LinearLayout {

    private TextView emptyView;
    private RecyclerView tweetsList;
    private TweetsAdapter tweetsAdapter;
    private SwipeRefreshLayout swipeLayout;
    private ScrollListener scrollListener;
    private boolean refreshingData;

    public TweetsPageView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TweetsPageView(Context context, AttributeSet attrs, int defStyleAttr) {
        this(context, attrs, defStyleAttr, 0);
    }

    public TweetsPageView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);

        super.setOrientation(VERTICAL);
    }

    @Override
    public void setOrientation(int orientation) {
        throw new UnsupportedOperationException("TweetsPageView doesn't support changing orientation");
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();

        emptyView = (TextView) findViewById(R.id.empty_view);
        tweetsList = (RecyclerView) findViewById(R.id.tweet_feed);
        swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_container);

        swipeLayout.setOnRefreshListener(() -> {
            if (refreshingData) {
                Timber.i("Timeline refresh already underway, ignoring new refresh request");
                return;
            }
            refreshTimeline();
        });
    }

    @Override
    public void setVisibility(@Visibility int visibility) {
        if (visibility == View.VISIBLE) {
            refreshTimeline();
        }
        super.setVisibility(visibility);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        initList();
    }

    private void initList() {

        Context context = getContext();
        String query = context.getString(R.string.social_query);

        if (!isInEditMode()) {
            SearchTimeline timeline = new SearchTimeline.Builder()
                    .resultType(SearchTimeline.ResultType.RECENT)
                    .maxItemsPerRequest(10)
                    .query(query)
                    .build();

            tweetsAdapter = new TweetsAdapter(timeline, context);
            tweetsList.setAdapter(tweetsAdapter);
        }

        emptyView.setText(context.getString(R.string.no_tweets_for_query, query));

        LinearLayoutManager layoutManager = (LinearLayoutManager) tweetsList.getLayoutManager();

        scrollListener = new ScrollListener(layoutManager) {
            @Override
            protected void loadMore() {
                tweetsAdapter.previous(new TimelineLoadingCallback());
            }
        };

        tweetsList.addOnScrollListener(scrollListener);
    }

    private void refreshTimeline() {
        swipeLayout.setRefreshing(true);
        refreshingData = true;
        scrollListener.reset();
        tweetsAdapter.refresh(new TimelineLoadingCallback());
    }

    private void onRefreshFinished() {
        refreshingData = false;

        if (tweetsAdapter.isEmpty()) {
            emptyView.setVisibility(VISIBLE);
            tweetsList.setVisibility(GONE);
        } else {
            emptyView.setVisibility(GONE);
            tweetsList.setVisibility(VISIBLE);
        }

        swipeLayout.setRefreshing(false);
        tweetsAdapter.notifyDataSetChanged();
    }

    public class TimelineLoadingCallback extends Callback<TimelineResult<Tweet>> {

        @Override
        public void success(Result<TimelineResult<Tweet>> result) {
            onRefreshFinished();
        }

        @Override
        public void failure(TwitterException exception) {
            onRefreshFinished();
            Timber.e(exception, "Error while refreshing the timeline.");
        }
    }
}

@@ -247,34 +247,8 @@
 et;%0A
-import android.view.View;%0A
 impo
@@ -271,32 +271,32 @@
 t.LinearLayout;%0A
+
 import android.w
@@ -644,53 +644,8 @@
 .R;%0A
-import net.squanchy.support.view.Visibility;%0A
 impo
@@ -2244,213 +2244,8 @@
  %7D%0A%0A
-    @Override%0A    public void setVisibility(@Visibility int visibility) %7B%0A        if (visibility == View.VISIBLE) %7B%0A            refreshTimeline();%0A        %7D%0A        super.setVisibility(visibility);%0A    %7D%0A%0A
     
@@ -3298,16 +3298,16 @@
     %7D;%0A%0A
-
         
@@ -3349,24 +3349,52 @@
 llListener);
+%0A%0A        refreshTimeline();
 %0A    %7D%0A%0A    

fix a crash happening on rotation