package com.graessle.movie_db.ui.activity;

import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.percent.PercentRelativeLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.graphics.Palette;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.util.StringBuilderPrinter;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.graessle.movie_db.R;
import com.graessle.movie_db.adapters.MovieDBPagerAdapter;
import com.graessle.movie_db.adapters.MovieListingPagerAdapter;
import com.graessle.movie_db.api.ApiClient;
import com.graessle.movie_db.api.MovieCallback;
import com.graessle.movie_db.api.call.MovieApi;
import com.graessle.movie_db.model.Cast;
import com.graessle.movie_db.model.CreditsResponse;
import com.graessle.movie_db.model.Genre;
import com.graessle.movie_db.model.Movie;
import com.graessle.movie_db.model.MoviesResponse;
import com.graessle.movie_db.utils.tab.SlidingTabLayout;
import com.graessle.movie_db.utils.tab.SlidingTabStrip;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;

import java.util.List;
import java.util.UUID;

import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Author: rgraessle
 * Created: 4/14/17.
 */

public class MovieListingActivity extends BaseActivityMenu {

    @Bind(R.id.BackdropImage) ImageView backdropImage;
    @Bind(R.id.PosterImage) ImageView posterImage;
    @Bind(R.id.Toolbar) Toolbar toolbar;
    @Bind(R.id.ToolbarTitle) TextView titleTxtView;
    @Bind(R.id.TitleCardView) PercentRelativeLayout titleCardView;
    @Bind(R.id.Tabs) SlidingTabLayout tabs;
    @Bind(R.id.MovieTitle) TextView movieTitle;
    @Bind(R.id.MovieGenre) TextView movieGenre;
    @Bind(R.id.LoginSignupPager)    ViewPager           viewPager;

    private static String TAG = MovieListingActivity.class.getSimpleName();

    private ProgressDialog progressDialog;

    private static final String MOVIE_ID_KEY = "MOVIE_ID";
    private int movieID;

    private List<Cast> castList;

    private Movie movieDetails;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_movie_listing);
        ButterKnife.bind(this);

        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            movieID = extras.getInt(MOVIE_ID_KEY);
        }

        loadMovie();

        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.getBackground().setAlpha(0);
        titleTxtView.setText("");
    }

    public SlidingTabLayout.TabColorizer getTabColorizer() {
        return new SlidingTabLayout.TabColorizer() {
            @Override
            public int getIndicatorColor(final int position) {
                return getResources().getColor(R.color.black);
            }
        };
    }

    private void loadCredits() {

        MovieApi.getCreditsByMovieId(this, movieID, getResources().getString(R.string.api_key), new MovieCallback() {
            @Override
            public void onSuccess(Response<?> response) {
                CreditsResponse moviesResponse = (CreditsResponse) response.body();

                castList = moviesResponse.getCast();
                setCast(castList);
                setData();
                setTabs();
            }

            @Override
            public void onFailure(int responseCode) {

            }
        }, UUID.randomUUID().toString());
    }

    private void loadMovie() {

        MovieApi.getMovieById(this, movieID, getResources().getString(R.string.api_key), new MovieCallback() {
            @Override
            public void onSuccess(Response<?> response) {
                movieDetails = (Movie) response.body();
                loadCredits();
            }

            @Override
            public void onFailure(int responseCode) {
                Log.e(TAG, "Failue: " + responseCode);
            }
        }, UUID.randomUUID().toString());
    }

    public void setData() {

        setMovieDetails(movieDetails);

        StringBuilder sb = new StringBuilder();
        int i = 1;
        for(Genre genre : movieDetails.getGenres()) {
            sb.append(genre.getName());
            if(i < movieDetails.getGenres().size()) {
                sb.append(", ");
            }
            i++;
        }

        movieTitle.setText(movieDetails.getTitle());
        movieGenre.setText(sb);

        Target target = new Target() {
            @Override
            public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                backdropImage.setImageBitmap(bitmap);
                Palette.from(bitmap)
                        .generate(new Palette.PaletteAsyncListener() {
                            @Override
                            public void onGenerated(Palette palette) {
                                Palette.Swatch textSwatch = palette.getMutedSwatch();
                                if(textSwatch == null) {
                                    titleCardView.setBackgroundColor(getResources().getColor(R.color.maximum_blue));
                                    tabs.setBackgroundColor(getResources().getColor(R.color.maximum_blue));
                                    return;
                                }
                                titleCardView.setBackgroundColor(textSwatch.getRgb());
                                tabs.setBackgroundColor(textSwatch.getRgb());
                            }
                        });
            }

            @Override
            public void onBitmapFailed(Drawable errorDrawable) {
                Log.e(TAG, errorDrawable.toString());
            }

            @Override
            public void onPrepareLoad(Drawable placeHolderDrawable) {

            }
        };

        backdropImage.setTag(target);

        if (!TextUtils.isEmpty(movieDetails.getBackdropPath())) {
            if(movieDetails.getBackdropPath() == null) {
                backdropImage.setBackgroundColor(getResources().getColor(R.color.cardview_dark_background));
                titleCardView.setBackgroundColor(getResources().getColor(R.color.maximum_blue));
                tabs.setBackgroundColor(getResources().getColor(R.color.maximum_blue));
            } else {
                Picasso.with(this).load(getResources().getString(R.string.backdrop_link) + movieDetails.getBackdropPath())
                        .into(target);
            }

        }

        if (!TextUtils.isEmpty(movieDetails.getPosterPath())) {
            Picasso.with(this).load(getResources().getString(R.string.image_link) + movieDetails.getPosterPath())
                    .error(R.color.cardview_dark_background)
                    .placeholder(R.color.cardview_dark_background)
                    .into(posterImage);
        }

    }

    public void setTabs() {
        final CharSequence[] titles = getResources().getStringArray(R.array.movie_listing_tabs);
        MovieListingPagerAdapter mPagerAdapter =
                new MovieListingPagerAdapter(getSupportFragmentManager(), titles.length, titles);

        viewPager.setAdapter(mPagerAdapter);
        tabs.setDistributeEvenly(true);

        tabs.setCustomTabColorizer(getTabColorizer());

        tabs.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                SlidingTabStrip strip = (SlidingTabStrip) tabs.getChildAt(0);

                TextView selectedTv = (TextView) strip.getChildAt(position);
                selectedTv.setTextColor(getResources().getColor(R.color.black));

                TextView unselectedTv = (TextView) strip.getChildAt((position + 1) % 2);
                unselectedTv.setTextColor(getResources().getColor(R.color.white));
            }

            @Override
            public void onPageSelected(int position) {
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
        tabs.setViewPager(viewPager);
    }

    public void setMovieDetails(Movie movie) {
        this.movieDetails = movie;
    }

    public Movie getMovieDetails() {
        Log.i(TAG, "movie details called: " + movieDetails.toString());
        return movieDetails;
    }

    public void setCast(List<Cast> cast) {
        this.castList = cast;
    }

    public List<Cast> getCast() {
        return castList;
    }
}
