package de.beyondsoft.ownchat.filepicker;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;

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

import de.beyondsoft.ownchat.R;
import de.beyondsoft.ownchat.filepicker.adapters.FileAdapterListener;
import de.beyondsoft.ownchat.filepicker.adapters.ImageGridAdapter;
import de.beyondsoft.ownchat.filepicker.models.ImageDirectory;
import de.beyondsoft.ownchat.filepicker.models.Media;
import de.beyondsoft.ownchat.filepicker.utils.AndroidLifecycleUtils;
import de.beyondsoft.ownchat.filepicker.utils.MediaStoreHelper;

public class MediaDetailsActivity extends BaseFilePickerActivity implements FileAdapterListener {
    private static final int SCROLL_THRESHOLD = 30;
    private RecyclerView recyclerView;
    private TextView emptyView;
    private RequestManager mGlideRequestManager;
    private ImageGridAdapter photoGridAdapter;
    private int fileType;

    @SuppressLint("MissingSuperCall")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState, R.layout.activity_media_details);
    }

    @Override
    protected void initView() {
        mGlideRequestManager = Glide.with(this);
        Intent intent = getIntent();
        if (intent != null) {

            fileType = intent.getIntExtra(FilePickerConst.EXTRA_FILE_TYPE,FilePickerConst.MEDIA_TYPE_IMAGE);
            ImageDirectory photoDirectory = intent.getParcelableExtra(ImageDirectory.class.getSimpleName());
            if(photoDirectory!=null) {

                setUpView(photoDirectory);
                if(getSupportActionBar()!=null)
                {
                    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
                    getSupportActionBar().setTitle(photoDirectory.getName());
                }
            }
        }
    }

    private void setUpView(ImageDirectory photoDirectory) {
        recyclerView = findViewById(R.id.recyclerview);
        emptyView = findViewById(R.id.empty_view);

        StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(3, OrientationHelper.VERTICAL);
        layoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                if (Math.abs(dy) > SCROLL_THRESHOLD) {
                    mGlideRequestManager.pauseRequests();
                } else {
                    resumeRequestsIfNotDestroyed();
                }
            }

            @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    resumeRequestsIfNotDestroyed();
                }
            }
        });

        getDataFromMedia(photoDirectory.getBucketId());
    }

    private void getDataFromMedia(String bucketId) {
        Bundle mediaStoreArgs = new Bundle();
        mediaStoreArgs.putBoolean(FilePickerConst.EXTRA_SHOW_GIF, false);
        mediaStoreArgs.putString(FilePickerConst.EXTRA_BUCKET_ID, bucketId);

        mediaStoreArgs.putInt(FilePickerConst.EXTRA_FILE_TYPE, fileType);

        if(fileType==FilePickerConst.MEDIA_TYPE_IMAGE) {
            MediaStoreHelper.getPhotoDirs(this, mediaStoreArgs, this::updateList);
        } else if(fileType==FilePickerConst.MEDIA_TYPE_VIDEO) {
            MediaStoreHelper.getVideoDirs(this, mediaStoreArgs, this::updateList);
        }
    }

    private void updateList(List<ImageDirectory> dirs) {
        ArrayList<Media> medias = new ArrayList<>();

        for (int i = 0; i < dirs.size(); i++) {
            medias.addAll(dirs.get(i).getMedias());
        }

        Collections.sort(medias, (a, b) -> b.getId() - a.getId());

        if(medias.size() > 0) {
            emptyView.setVisibility(View.GONE);
            recyclerView.setVisibility(View.VISIBLE);
        } else {
            emptyView.setVisibility(View.VISIBLE);
            recyclerView.setVisibility(View.GONE);
            return;
        }

        if(photoGridAdapter!=null) {
            photoGridAdapter.setData(medias);
            photoGridAdapter.notifyDataSetChanged();
        } else {
            photoGridAdapter = new ImageGridAdapter(this, medias,PickerManager.getInstance().getSelectedPhotos(),false, this);
            recyclerView.setAdapter(photoGridAdapter);
        }
    }

    private void resumeRequestsIfNotDestroyed() {
        if (!AndroidLifecycleUtils.canLoadImage(this)) {
            return;
        }

        mGlideRequestManager.resumeRequests();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.picker_menu, menu);

        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int i = item.getItemId();
        if (i == R.id.action_done) {
            setResult(RESULT_OK, null);
            finish();

            return true;
        } else if (i == android.R.id.home) {
            onBackPressed();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onItemSelected() {
        if(PickerManager.getInstance().getMaxCount()==1) {
            setResult(RESULT_OK, null);
            finish();
        }
    }

    @Override
    public void onBackPressed() {
        setResult(RESULT_CANCELED, null);
        finish();
    }
}
