ca.zadrox.dota2esportticker.ui.MatchDetailActivity.java Source code

Java tutorial

Introduction

Here is the source code for ca.zadrox.dota2esportticker.ui.MatchDetailActivity.java

Source

/*
 * Copyright 2014 Nicholas Liu
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package ca.zadrox.dota2esportticker.ui;

import android.app.ActivityOptions;
import android.app.LoaderManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.Loader;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.Toolbar;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.animation.DecelerateInterpolator;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;

import ca.zadrox.dota2esportticker.R;
import ca.zadrox.dota2esportticker.data.MatchContract;
import ca.zadrox.dota2esportticker.data.gson.model.DotaGameData;
import ca.zadrox.dota2esportticker.data.gson.model.Game;
import ca.zadrox.dota2esportticker.data.http.match.model.Match;
import ca.zadrox.dota2esportticker.data.http.match.model.Player;
import ca.zadrox.dota2esportticker.data.http.match.model.RecentMatch;
import ca.zadrox.dota2esportticker.data.http.match.model.Team;
import ca.zadrox.dota2esportticker.ui.widget.BezelImageView;
import ca.zadrox.dota2esportticker.ui.widget.CheckableFrameLayout;
import ca.zadrox.dota2esportticker.ui.widget.ExpandableHeightGridView;
import ca.zadrox.dota2esportticker.ui.widget.MessageCardView;
import ca.zadrox.dota2esportticker.ui.widget.ObservableScrollView;
import ca.zadrox.dota2esportticker.util.LogUtils;
import ca.zadrox.dota2esportticker.util.MatchDetailLoader;
import ca.zadrox.dota2esportticker.util.ReminderHelper;
import ca.zadrox.dota2esportticker.util.StringUtils;
import ca.zadrox.dota2esportticker.util.TimeUtils;
import ca.zadrox.dota2esportticker.util.UIUtils;
import ca.zadrox.dota2esportticker.util.steamapi.SAPILiveGamesLoader;
import ca.zadrox.dota2esportticker.util.steamapi.SteamAuth;
import ca.zadrox.dota2esportticker.util.xform.CropImageTransform;
import ca.zadrox.dota2esportticker.util.xform.RoundedTransformation;
import ca.zadrox.dota2esportticker.util.xform.TopRoundedTransformation;

/**
 * Created by Acco on 10/28/2014.
 */
public class MatchDetailActivity extends BaseActivity implements ObservableScrollView.Callbacks {
    public static final String ARGS_MATCH_URL = "match_url";
    public static final String ARGS_GG_MATCH_ID = "gg_match_id";

    private static final String TAG = MatchDetailActivity.class.getSimpleName();
    private static final float PHOTO_ASPECT_RATIO = 1.5f;
    private static final int TIME_HINT_UPDATE_INTERVAL = 30000; // 30s

    private static final String[] UPCOMING_COLUMNS = {
            MatchContract.SeriesEntry.TABLE_NAME + "." + MatchContract.SeriesEntry._ID,
            MatchContract.SeriesEntry.COLUMN_DATETIME, MatchContract.SeriesEntry.COLUMN_BEST_OF,
            MatchContract.SeriesEntry.COLUMN_TEAM_ONE_NAME, MatchContract.SeriesEntry.COLUMN_PATH_TEAM_ONE_FLAG,
            MatchContract.SeriesEntry.COLUMN_TEAM_TWO_NAME, MatchContract.SeriesEntry.COLUMN_PATH_TEAM_TWO_FLAG,
            MatchContract.SeriesEntry.COLUMN_TOURNAMENT_NAME, MatchContract.SeriesEntry.COLUMN_PATH_TOURNAMENT_LOGO,
            MatchContract.SeriesEntry.COLUMN_TOURNAMENT_URL, MatchContract.SeriesEntry.COLUMN_GG_MATCH_PAGE,
            MatchContract.ReminderEntry.COLUMN_SET_REMINDER };
    private final int DB_LOADER = 0;
    private final int GGNET_LOADER = 1;
    private final int STEAM_LOADER = 2;

    private Handler mHandler = new Handler();
    private CheckableFrameLayout mAddReminderButton;

    private long mMatchStart;
    private long mGGnetMatchId;
    private String mTitleString;
    private String mUrl;
    private String mMatchScore;
    private boolean mStarred;
    private boolean mInitStarred;
    private MenuItem mShareMenuItem;
    private View mScrollViewChild;
    private TextView mTitle;
    private TextView mSubtitle;
    private ObservableScrollView mScrollView;
    private View mHeaderBox;
    private ViewGroup mDetailsContainer;
    private List<Runnable> mDeferredUiOperations = new ArrayList<Runnable>();
    private StringBuilder mBuffer = new StringBuilder();
    private int mPhotoHeightPixels;
    private int mHeaderHeightPixels;
    private int mAddReminderButtonHeightPixels;
    private ViewTreeObserver.OnGlobalLayoutListener mGlobalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            mAddReminderButtonHeightPixels = mAddReminderButton.getHeight();
            recomputePhotoAndScrollingMetrics();
        }
    };
    private boolean mHasPhoto;
    private View mMatchViewContainer;
    private ImageView mMatchImageView;
    private ImageView mMatchTeamOneImageView;
    private ImageView mMatchTeamTwoImageView;
    private TextView mMatchScoreView;
    private TextView mBestOfView;
    private Runnable mTimeHintUpdaterRunnable = null;
    private Context mContext = this;

    private View mTeamCardOne;
    private View mTeamCardTwo;

    private LoaderManager.LoaderCallbacks<Cursor> mCursorCallbacks = new LoaderManager.LoaderCallbacks<Cursor>() {
        @Override
        public Loader<Cursor> onCreateLoader(int id, Bundle args) {
            Uri resultsUri;
            resultsUri = MatchContract.ReminderEntry
                    .buildReminderUri(getIntent().getLongExtra(ARGS_GG_MATCH_ID, 0));

            LogUtils.LOGD(TAG, resultsUri.toString());

            return new CursorLoader(mContext, resultsUri, UPCOMING_COLUMNS, null, null, null);
        }

        @Override
        public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
            LogUtils.LOGD(TAG, data.toString());
            updateContentFromCursor(data);
        }

        @Override
        public void onLoaderReset(Loader<Cursor> loader) {

        }
    };
    // to be used with the httpgetter.
    private LoaderManager.LoaderCallbacks<Match> mMatchCallbacks = new LoaderManager.LoaderCallbacks<Match>() {
        @Override
        public Loader<Match> onCreateLoader(int id, Bundle args) {
            MatchDetailLoader loader = new MatchDetailLoader(mContext, mUrl);

            return loader;
        }

        @Override
        public void onLoadFinished(Loader<Match> loader, Match data) {
            if (data != null) {
                updateContentFromGG(data);
            } else {
                Toast.makeText(mContext, "No Connection", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onLoaderReset(Loader<Match> loader) {
            loader.cancelLoad();
        }
    };
    private LoaderManager.LoaderCallbacks<DotaGameData[]> mLiveGameLoaderCallbacks = new LoaderManager.LoaderCallbacks<DotaGameData[]>() {
        @Override
        public Loader<DotaGameData[]> onCreateLoader(int id, Bundle args) {
            return new SAPILiveGamesLoader(mContext, 0);
        }

        @Override
        public void onLoadFinished(Loader<DotaGameData[]> loader, DotaGameData[] data) {
            updateContentFromSAPI(data);
        }

        @Override
        public void onLoaderReset(Loader<DotaGameData[]> loader) {

        }
    };
    private float mMaxHeaderElevation;
    private float mFABElevation;
    private String dateTime;
    private String bestOf;
    private String teamLeftName;
    private String teamRightName;
    private String teamLeftFlagUrl;
    private String teamRightFlagUrl;
    private String tournamentName;
    private String tournamentLogo;
    private String tournamentUrl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_matches_detail);

        final Toolbar toolbar = getActionBarToolbar();
        toolbar.setNavigationIcon(R.drawable.ic_up);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

        mHandler.post(new Runnable() {
            @Override
            public void run() {
                toolbar.setTitle("");
            }
        });

        //setmUrl();

        mFABElevation = getResources().getDimensionPixelSize(R.dimen.fab_elevation);
        mMaxHeaderElevation = getResources().getDimensionPixelSize(R.dimen.session_detail_max_header_elevation);

        mScrollView = (ObservableScrollView) findViewById(R.id.scroll_view);
        mScrollView.addCallbacks(this);
        ViewTreeObserver vto = mScrollView.getViewTreeObserver();
        if (vto.isAlive()) {
            vto.addOnGlobalLayoutListener(mGlobalLayoutListener);
        }

        mScrollViewChild = findViewById(R.id.scroll_view_child);
        // mScrollViewChild.setVisibility(View.INVISIBLE);

        mDetailsContainer = (ViewGroup) findViewById(R.id.details_container);
        mDetailsContainer.setY(2000);
        mHeaderBox = findViewById(R.id.header_match);
        mTitle = (TextView) findViewById(R.id.header_title);
        mSubtitle = (TextView) findViewById(R.id.header_subtitle);
        mMatchViewContainer = findViewById(R.id.match_photo_container);
        //mMatchViewContainer.setVisibility(View.INVISIBLE);
        mMatchTeamOneImageView = (ImageView) findViewById(R.id.match_team_one_photo);
        mMatchTeamTwoImageView = (ImageView) findViewById(R.id.match_team_two_photo);
        mMatchImageView = (ImageView) findViewById(R.id.match_photo);
        mMatchScoreView = (TextView) findViewById(R.id.match_score_view);
        mBestOfView = (TextView) findViewById(R.id.match_bo);

        mAddReminderButton = (CheckableFrameLayout) findViewById(R.id.add_schedule_button);
        mAddReminderButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                boolean starred = !mStarred;
                showStarred(starred, true);
                setSessionStarred(starred);
            }
        });

        mGGnetMatchId = getIntent().getLongExtra(ARGS_GG_MATCH_ID, 0);

        mMatchImageView.setColorFilter(Color.rgb(123, 123, 123), android.graphics.PorterDuff.Mode.MULTIPLY);

        DisplayMetrics displayMetrics = getResources().getDisplayMetrics();

        final int dWidth = displayMetrics.widthPixels * 2 / 3;

        Picasso.with(this).load(R.drawable.drawable_dota_bg_dire_ancient).config(Bitmap.Config.ARGB_8888)
                .resize(Math.round(dWidth * PHOTO_ASPECT_RATIO), dWidth)
                .transform(new CropImageTransform(displayMetrics.heightPixels, displayMetrics.widthPixels))
                .into(mMatchImageView);

        LoaderManager manager = getLoaderManager();
        mHasPhoto = true;

        manager.initLoader(DB_LOADER, null, mCursorCallbacks);
    }

    private void recomputePhotoAndScrollingMetrics() {
        mHeaderHeightPixels = mHeaderBox.getHeight();

        mPhotoHeightPixels = 0;
        if (mHasPhoto) {
            mPhotoHeightPixels = (int) (mMatchViewContainer.getWidth() / PHOTO_ASPECT_RATIO);
            mPhotoHeightPixels = Math.min(mPhotoHeightPixels, mScrollView.getHeight() * 2 / 3);
        }

        ViewGroup.LayoutParams lp;
        lp = mMatchViewContainer.getLayoutParams();
        if (lp.height != mPhotoHeightPixels) {
            lp.height = mPhotoHeightPixels;
            mMatchViewContainer.setLayoutParams(lp);
        }

        ViewGroup.MarginLayoutParams mlp = (ViewGroup.MarginLayoutParams) mDetailsContainer.getLayoutParams();
        if (mlp.topMargin != mHeaderHeightPixels + mPhotoHeightPixels) {
            mlp.topMargin = mHeaderHeightPixels + mPhotoHeightPixels;
            mDetailsContainer.setLayoutParams(mlp);
        }

        onScrollChanged(0, 0); // trigger scroll handling
    }

    private void showStarredDeferred(final boolean starred, final boolean allowAnimate) {
        mDeferredUiOperations.add(new Runnable() {
            @Override
            public void run() {
                showStarred(starred, allowAnimate);
            }
        });
        tryExecuteDeferredUiOperations();
    }

    private void showStarred(boolean starred, boolean allowAnimate) {
        mStarred = starred;

        mAddReminderButton.setChecked(mStarred, allowAnimate);

        ImageView iconView = (ImageView) mAddReminderButton.findViewById(R.id.add_schedule_icon);
        getLUtils().setOrAnimatePlusCheckIcon(iconView, starred, allowAnimate);
    }

    private void tryExecuteDeferredUiOperations() {
        for (Runnable r : mDeferredUiOperations) {
            r.run();
        }
        mDeferredUiOperations.clear();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mScrollView == null) {
            return;
        }

        ViewTreeObserver vto = mScrollView.getViewTreeObserver();
        if (vto.isAlive()) {
            vto.removeOnGlobalLayoutListener(mGlobalLayoutListener);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mTimeHintUpdaterRunnable != null) {
            mHandler.postDelayed(mTimeHintUpdaterRunnable, TIME_HINT_UPDATE_INTERVAL);
        }

        LocalBroadcastManager.getInstance(this).registerReceiver(mSteamAPIKeyIncorrectReceiver,
                new IntentFilter(SteamAuth.STEAM_API_KEY_INCORRECT));
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mInitStarred != mStarred) {
            if (TimeUtils.getUTCTime() < mMatchStart) {
                if (mStarred) {
                    ReminderHelper.setupNotification(this, mMatchStart, mGGnetMatchId);
                } else if (!mStarred) {
                    ReminderHelper.cancelNotification(this, mMatchStart, mGGnetMatchId);
                }
            }
        }
    }

    private void setTextSelectable(TextView tv) {
        if (tv != null && !tv.isTextSelectable()) {
            tv.setTextIsSelectable(true);
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        overridePendingTransition(R.anim.anim_scale_in, R.anim.anim_slide_out);
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mTimeHintUpdaterRunnable != null) {
            mHandler.removeCallbacks(mTimeHintUpdaterRunnable);
        }

        LocalBroadcastManager.getInstance(this).unregisterReceiver(mSteamAPIKeyIncorrectReceiver);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        //getMenuInflater().inflate(R.menu.session_detail, menu);
        //mSocialStreamMenuItem = menu.findItem(R.id.menu_social_stream);
        //mShareMenuItem = menu.findItem(R.id.menu_share);
        //tryExecuteDeferredUiOperations();
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return false;
    }

    private void setmUrl() {
        mUrl = getIntent().getStringExtra(ARGS_MATCH_URL);
        LogUtils.LOGD(TAG, mUrl);
    }

    @Override
    public void onScrollChanged(int deltaX, int deltaY) {
        // Reposition the header bar -- it's normally anchored to the top of the content,
        // but locks to the top of the screen on scroll
        int scrollY = mScrollView.getScrollY();

        float newTop = Math.max(mPhotoHeightPixels, scrollY);
        mHeaderBox.setTranslationY(newTop);
        mAddReminderButton.setTranslationY(newTop + mHeaderHeightPixels - mAddReminderButtonHeightPixels / 2);

        float gapFillProgress = 1;
        if (mPhotoHeightPixels != 0) {
            gapFillProgress = Math.min(Math.max(UIUtils.getProgress(scrollY, 0, mPhotoHeightPixels), 0), 1);
        }

        ViewCompat.setElevation(mHeaderBox, gapFillProgress * mMaxHeaderElevation);
        ViewCompat.setElevation(mAddReminderButton, gapFillProgress * mMaxHeaderElevation + mFABElevation);

        // Move background photo (parallax effect)
        mMatchViewContainer.setTranslationY(scrollY * 0.28f);
    }

    private void updateContentFromCursor(Cursor c) {
        if (c.moveToFirst()) {
            dateTime = c.getString(1);
            bestOf = c.getString(2);
            teamLeftName = c.getString(3);
            teamLeftFlagUrl = c.getString(4);
            teamRightName = c.getString(5);
            teamRightFlagUrl = c.getString(6);
            tournamentName = c.getString(7);
            tournamentLogo = c.getString(8);
            tournamentUrl = c.getString(9);
            mUrl = c.getString(10);

            mMatchStart = Long.parseLong(dateTime);

            mTitle.setText(teamLeftName + " vs " + teamRightName);
            mSubtitle.setText(TimeUtils.toReadableLocalTime(dateTime));
            mBestOfView.setText(bestOf.toUpperCase());

            View tournamentCard = getLayoutInflater().inflate(R.layout.card_tournament, mDetailsContainer, false);

            ImageView tournamentLogoView = (ImageView) tournamentCard.findViewById(R.id.card_tournament_logo);
            TextView tournamentNameView = (TextView) tournamentCard.findViewById(R.id.card_tournament_details);

            DisplayMetrics dm = mContext.getResources().getDisplayMetrics();

            int rpx = Math.round(UIUtils.dpToPx(dm, 3f));

            tournamentLogoView.setColorFilter(Color.rgb(123, 123, 123), android.graphics.PorterDuff.Mode.MULTIPLY);

            Picasso.with(this).load(teamLeftFlagUrl).transform(new RoundedTransformation(rpx, 0)).fit()
                    .into(mMatchTeamOneImageView);

            Picasso.with(this).load(teamRightFlagUrl).transform(new RoundedTransformation(rpx, 0)).fit()
                    .into(mMatchTeamTwoImageView);

            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                Picasso.with(this).load(tournamentLogo).transform(new TopRoundedTransformation(rpx)).fit()
                        .centerCrop().into(tournamentLogoView);
            } else {
                Picasso.with(this).load(tournamentLogo).into(tournamentLogoView);
            }

            tournamentNameView.setText(tournamentName);

            final Uri tournamentLink = Uri.parse(tournamentUrl);

            tournamentCard.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(Intent.ACTION_VIEW, tournamentLink);
                    startActivity(intent);
                }
            });

            mDetailsContainer.addView(tournamentCard);

            mAddReminderButton.setVisibility(View.VISIBLE);

            final boolean isReminderSet = c.getInt(11) != 0;

            showStarredDeferred(mInitStarred = isReminderSet, false);

            getLoaderManager().initLoader(GGNET_LOADER, null, mMatchCallbacks);
            getLoaderManager().initLoader(STEAM_LOADER, null, mLiveGameLoaderCallbacks);

        } else {
            return;
        }
    }

    private void updateContentFromGG(Match data) {

        if (data == null) {
            Toast.makeText(this, "Network Connection issues", Toast.LENGTH_SHORT).show();
            return;
        }

        if (Long.parseLong(dateTime) < TimeUtils.getUTCTime()) {
            mMatchScoreView.setText(data.teamOne.score + " : " + data.teamTwo.score);
        } else {
            mMatchScoreView.setText(" vs ");
        }

        if (data.livestreams != null && data.livestreams.length != 0) {
            final ViewGroup livestreamsCard = (ViewGroup) getLayoutInflater().inflate(R.layout.card_livestream,
                    mDetailsContainer, false);
            final ViewGroup livestreamsBlock = (ViewGroup) livestreamsCard
                    .findViewById(R.id.card_livestreams_block);
            for (int i = 0; i < data.livestreams.length; i++) {
                if (data.livestreams[i].url == null) {
                    continue;
                }
                final View livestreamItem = getLayoutInflater().inflate(R.layout.livestream_detail,
                        livestreamsBlock, false);
                final TextView livestreamNameView = (TextView) livestreamItem
                        .findViewById(R.id.livestream_name_view);
                final TextView livestreamServiceView = (TextView) livestreamItem
                        .findViewById(R.id.livestream_service_view);

                final Uri livestreamUri = Uri.parse(data.livestreams[i].url);

                livestreamNameView
                        .setText(data.livestreams[i].language.toUpperCase() + " - " + data.livestreams[i].title);
                livestreamServiceView
                        .setText(data.livestreams[i].url.contains("twitch.tv") ? "Twitch.tv" : "DailyMotion");

                livestreamItem.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent viewLivestreamIntent = new Intent(Intent.ACTION_VIEW, livestreamUri);
                        startActivity(viewLivestreamIntent);
                    }
                });

                livestreamsBlock.addView(livestreamItem);

                final View divider = getLayoutInflater().inflate(R.layout.divider, livestreamsBlock, false);
                livestreamsBlock.addView(divider);
            }

            mDetailsContainer.addView(livestreamsCard, 1);

        }

        if (data.vods != null && data.vods.length != 0) {
            final ViewGroup vodsCard = (ViewGroup) getLayoutInflater().inflate(R.layout.card_vods,
                    mDetailsContainer, false);
            final ViewGroup vodsBlock = (ViewGroup) vodsCard.findViewById(R.id.card_vods_block);
            for (int i = 0; i < data.vods.length; i++) {
                final TextView vodsItem = (TextView) getLayoutInflater().inflate(R.layout.vod_detail, vodsBlock,
                        false);

                vodsItem.setText(data.vods[i].vodDesc);

                final Uri vodUri = Uri.parse(data.vods[i].vodUrl);

                vodsItem.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent viewVodIntent = new Intent(Intent.ACTION_VIEW, vodUri);
                        startActivity(viewVodIntent);
                    }
                });

                vodsBlock.addView(vodsItem);

                final View divider = getLayoutInflater().inflate(R.layout.divider, vodsBlock, false);
                vodsBlock.addView(divider);
            }

            mDetailsContainer.addView(vodsCard, 2);

        }

        data.teamOne.flagUrl = teamLeftFlagUrl;
        data.teamTwo.flagUrl = teamRightFlagUrl;
        data.teamOne.name = teamLeftName;
        data.teamTwo.name = teamRightName;

        mTeamCardOne = makeTeamView(data.teamOne, mDetailsContainer);
        mTeamCardTwo = makeTeamView(data.teamTwo, mDetailsContainer);

        mDetailsContainer.addView(mTeamCardOne);
        mDetailsContainer.addView(mTeamCardTwo);

        mMatchTeamOneImageView.setClickable(true);
        mMatchTeamTwoImageView.setClickable(true);

        mMatchTeamOneImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mScrollView.smoothScrollTo(0,
                        Math.round(mTeamCardOne.getY() + mTeamCardOne.getHeight() - mHeaderHeightPixels));
            }
        });

        mMatchTeamTwoImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mScrollView.smoothScrollTo(0,
                        Math.round(mTeamCardTwo.getY() + mTeamCardTwo.getHeight() - mHeaderHeightPixels));
            }
        });

        final ViewGroup extrasCard = (ViewGroup) getLayoutInflater().inflate(R.layout.card_links, mDetailsContainer,
                false);

        final ViewGroup extrasBlock = (ViewGroup) extrasCard.findViewById(R.id.card_links_block);

        final TextView extrasItem = (TextView) getLayoutInflater().inflate(R.layout.link_item, extrasBlock, false);

        extrasItem.setText("GosuGamers Match Page");

        extrasItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent viewGGNetMatchPage = new Intent(Intent.ACTION_VIEW, Uri.parse(mUrl));
                startActivity(viewGGNetMatchPage);
            }
        });

        extrasBlock.addView(extrasItem);

        mDetailsContainer.addView(extrasCard);

        mMatchViewContainer.setBackground(null);
        //getWindow().setBackgroundDrawable(null);

        mDetailsContainer.animate().translationY(0).setDuration(350).setInterpolator(new DecelerateInterpolator())
                .start();

    }

    private void updateContentFromSAPI(DotaGameData[] data) {

        String tOn = teamLeftName;
        String tTn = teamRightName;

        long matchId = 0;

        if (data != null && data.length != 0) {
            for (DotaGameData gameData : data) {
                if (gameData.getType() != DotaGameData.LIVE_DATA) {
                    continue;
                }

                gameData = (Game) gameData;

                if (((Game) gameData).dire_team != null && ((Game) gameData).radiant_team != null) {

                    String sRn = ((Game) gameData).radiant_team.team_name;
                    String sDn = ((Game) gameData).dire_team.team_name;

                    if (StringUtils.areTeamsPlaying(tOn, tTn, sRn, sDn)) {
                        matchId = ((Game) gameData).match_id;
                        break;
                    }

                }
            }
        }

        if (matchId == 0) {
            return;
        }

        final MessageCardView mSteamCard = (MessageCardView) mDetailsContainer.findViewById(R.id.card_live_stats);

        mSteamCard.show();

        final Intent viewLiveGameDetails = new Intent(this, LiveGameStatsActivity.class);
        viewLiveGameDetails.putExtra(LiveGameStatsActivity.ARGS_GAME_TLL, teamLeftFlagUrl);
        viewLiveGameDetails.putExtra(LiveGameStatsActivity.ARGS_GAME_TLR, teamRightFlagUrl);
        viewLiveGameDetails.putExtra(LiveGameStatsActivity.ARGS_GAME_BO, bestOf);
        viewLiveGameDetails.putExtra(LiveGameStatsActivity.ARGS_GAME_TNL, teamLeftName);
        viewLiveGameDetails.putExtra(LiveGameStatsActivity.ARGS_GAME_TNR, teamRightName);
        viewLiveGameDetails.putExtra(LiveGameStatsActivity.ARGS_GAME_TN, tournamentName);
        viewLiveGameDetails.putExtra(LiveGameStatsActivity.ARGS_GAME_MID, matchId);

        mSteamCard.setListener(new MessageCardView.OnMessageCardButtonClicked() {
            @Override
            public void onMessageCardButtonClicked(String tag) {
                if ("VIEW_NOW".equals(tag)) {
                    startActivity(viewLiveGameDetails, ActivityOptions
                            .makeCustomAnimation(mContext, R.anim.anim_slide_in, R.anim.anim_scale_out).toBundle());
                } else {
                    mSteamCard.dismiss(true);
                }
            }
        });
    }

    private View makeTeamView(Team team, ViewGroup root) {

        ViewGroup teamView = (ViewGroup) getLayoutInflater().inflate(R.layout.card_team, root, false);
        TextView teamName = (TextView) teamView.findViewById(R.id.card_team_name);
        BezelImageView teamLogo = (BezelImageView) teamView.findViewById(R.id.card_team_logo);
        ExpandableHeightGridView teamContent = (ExpandableHeightGridView) teamView
                .findViewById(R.id.card_team_gridview);

        final Uri teamUri = Uri.parse(team.teamUrl);
        (teamView.findViewById(R.id.card_team_link)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(Intent.ACTION_VIEW, teamUri));
            }
        });

        TextView bettingOdds = (TextView) teamView.findViewById(R.id.card_team_gosubet);

        if (team.gosubetTie != null) {
            teamView.findViewById(R.id.card_team_gb_windraw).setVisibility(View.VISIBLE);
            bettingOdds.setText(team.gosubetWin + "\n" + team.gosubetTie);
        } else {
            bettingOdds.setText(team.gosubetWin);
        }

        if (team.recPerf != null) {
            RecentPerfAdapter mAdapter = new RecentPerfAdapter(this, R.layout.grid_recent_perf, team.recPerf);

            teamContent.setExpanded(true);
            teamName.setText(team.name);
            Picasso.with(this).load(team.flagUrl).into(teamLogo);
            teamContent.setAdapter(mAdapter);
            teamContent.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    RecentMatch match = (RecentMatch) parent.getAdapter().getItem(position);
                    final Uri uri = Uri.parse(match.matchUrl);
                    startActivity(new Intent(Intent.ACTION_VIEW, uri));
                }
            });

        } else if (team.players != null) {
            TextView contentDescriptor = (TextView) teamView.findViewById(R.id.card_team_content_descriptor);
            PlayerAdapter mAdapter = new PlayerAdapter(this, R.layout.grid_player, team.players);

            contentDescriptor.setText("Players:");
            teamContent.setExpanded(true);

            teamContent.setColumnWidth(Math.round(UIUtils.dpToPx(getResources().getDisplayMetrics(), 120f)));
            teamName.setText(team.name);
            Picasso.with(this).load(team.flagUrl).into(teamLogo);
            teamContent.setAdapter(mAdapter);

            teamContent.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Player mPlayer = (Player) parent.getAdapter().getItem(position);
                    final Uri uri = Uri.parse(mPlayer.profilePageUrl);
                    startActivity(new Intent(Intent.ACTION_VIEW, uri));
                }
            });
        }

        return teamView;
    }

    public void setSessionStarred(boolean starred) {

        if (mGGnetMatchId == -1) {
            return;
        }

        ReminderHelper.setMatchStarred(this, mGGnetMatchId, starred);
    }

    private BroadcastReceiver mSteamAPIKeyIncorrectReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(context, "Steam Web API Key incorrect. Double check settings.", Toast.LENGTH_SHORT)
                    .show();
        }
    };

    private class RecentPerfAdapter extends ArrayAdapter<RecentMatch> {

        public RecentPerfAdapter(Context context, int layoutRes, RecentMatch[] recentMatches) {
            super(context, layoutRes, recentMatches);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            RecentMatch recentMatch = getItem(position);
            if (convertView == null) {
                LayoutInflater layoutInflater = (LayoutInflater) getContext()
                        .getSystemService(LAYOUT_INFLATER_SERVICE);
                convertView = layoutInflater.inflate(R.layout.grid_recent_perf, parent, false);
            }

            TextView teamName = (TextView) convertView.findViewById(R.id.grid_team_name);
            teamName.setText(recentMatch.vsTeamName);
            TextView score = (TextView) convertView.findViewById(R.id.grid_text_score);
            score.setText(recentMatch.mScore + " : " + recentMatch.vsScore);

            switch (recentMatch.result) {
            case RecentMatch.LOSS:
                score.setBackgroundColor(getContext().getResources().getColor(R.color.grid_loss));
                break;
            case RecentMatch.DRAW:
                score.setBackgroundColor(getContext().getResources().getColor(R.color.grid_tie));
                break;
            case RecentMatch.WIN:
                score.setBackgroundColor(getContext().getResources().getColor(R.color.grid_win));
                break;
            default:
                break;
            }

            ImageView teamLogo = (ImageView) convertView.findViewById(R.id.grid_team_logo);

            teamLogo.setColorFilter(Color.rgb(123, 123, 123), android.graphics.PorterDuff.Mode.MULTIPLY);

            Picasso.with(getContext()).load(recentMatch.vsTeamLogo).into(teamLogo);

            return convertView;
        }
    }

    private class PlayerAdapter extends ArrayAdapter<Player> {

        public PlayerAdapter(Context context, int layoutRes, Player[] recentMatches) {
            super(context, layoutRes, recentMatches);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Player player = getItem(position);
            if (convertView == null) {
                LayoutInflater layoutInflater = (LayoutInflater) getContext()
                        .getSystemService(LAYOUT_INFLATER_SERVICE);
                convertView = layoutInflater.inflate(R.layout.grid_player, parent, false);
            }

            TextView playerName = (TextView) convertView.findViewById(R.id.grid_player_name);
            playerName.setText(player.name);

            if (player.isStandin) {
                convertView.findViewById(R.id.grid_player_standin).setVisibility(View.VISIBLE);
            }

            return convertView;
        }
    }
}