/*
 * Copyright 2018 Yan Zhenjie.
 *
 * 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 com.sobot.album.app.gallery;

import android.app.Activity;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.viewpager.widget.ViewPager;

import com.sobot.album.AlbumFile;
import com.sobot.album.R;
import com.sobot.album.SobotAlbum;
import com.sobot.album.api.widget.Widget;
import com.sobot.album.app.Contract;
import com.sobot.album.app.fragment.ImageFragment;
import com.sobot.album.app.fragment.SobotViewPagerAdapter;
import com.sobot.album.app.fragment.VideoFragment;

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

public class GalleryView<Data> extends Contract.GalleryView<Data> implements View.OnClickListener {

    private Activity mActivity;

//    private MenuItem mCompleteMenu;

    private ViewPager mViewPager;
    private LinearLayout mLayoutBottom;
    private TextView mTvDuration;
    private TextView sobot_tv_select;//已选多少张
    private TextView sobot_tv_add;//添加到
    private TextView sobot_tv_title;//预览已选时显示预览进度
    private CheckBox mCheckBox;
    private FrameLayout mLayoutLayer;
    private int listSize;//显示的数量
    private boolean showTitle = false;//是否显示头部
    private int selectCount;//选中的数量
    private HorizontalScrollView scrollView;//横向滑动
    private LinearLayout sobot_thumbnail_ll;//横向滑动
    private SobotViewPagerAdapter pagerAdapter;
    private List<Fragment> fragments;
    private FragmentManager fragmentManager;

    public GalleryView(Activity activity, FragmentManager fragmentManager, Contract.GalleryPresenter presenter) {
        super(activity, presenter);
        this.mActivity = activity;
        this.fragmentManager = fragmentManager;
        this.mViewPager = activity.findViewById(R.id.view_pager);
        this.mLayoutBottom = activity.findViewById(R.id.layout_bottom);
        this.mTvDuration = activity.findViewById(R.id.tv_duration);
        this.mCheckBox = activity.findViewById(R.id.check_box);
        this.mLayoutLayer = activity.findViewById(R.id.layout_layer);
        this.sobot_tv_select = activity.findViewById(R.id.sobot_tv_select);
        this.sobot_tv_add = activity.findViewById(R.id.sobot_tv_add);
        this.sobot_tv_title = activity.findViewById(R.id.sobot_text_title_center);
        this.scrollView = activity.findViewById(R.id.sobot_hscroll_view);
        this.sobot_thumbnail_ll = activity.findViewById(R.id.sobot_thumbnail_ll);

        this.mCheckBox.setOnClickListener(this);
        this.sobot_tv_add.setOnClickListener(this);
        this.mLayoutLayer.setOnClickListener(this);
    }

    public void setShowTitle(boolean showTitle) {
        this.showTitle = showTitle;
    }

    @Override
    protected void onCreateOptionsMenu(Menu menu) {
//        getMenuInflater().inflate(R.menu.album_menu_gallery, menu);
//        mCompleteMenu = menu.findItem(R.id.album_menu_finish);
    }

    @Override
    protected void onOptionsItemSelected(MenuItem item) {
//        int id = item.getItemId();
//        if (id == R.id.album_menu_finish) {
//            getPresenter().complete();
//        }
    }

    @Override
    public void setupViews(Widget widget, boolean checkable) {
//        SystemBar.invasionStatusBar(mActivity);
//        SystemBar.invasionNavigationBar(mActivity);
//        SystemBar.setStatusBarColor(mActivity, Color.TRANSPARENT);
//        SystemBar.setNavigationBarColor(mActivity, getColor(R.color.albumSheetBottom));

//        setHomeAsUpIndicator(R.drawable.album_ic_back_white);
//        if (!checkable) {
//            mCompleteMenu.setVisible(false);
//            mCheckBox.setVisibility(View.GONE);
//        } else {
//            ColorStateList itemSelector = widget.getMediaItemCheckSelector();
//            mCheckBox.setSupportButtonTintList(itemSelector);
//            mCheckBox.setTextColor(itemSelector);
//        }

        mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                getPresenter().onCurrentChanged(position);
                if (showTitle) {
                    String title = (position + 1) + "/" + listSize;
                    sobot_tv_title.setText(title);
                    sobot_tv_title.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    @Override
    public void bindData(List<Data> dataList) {
        listSize = dataList.size();
        if (showTitle) {
            String title = "1/" + listSize;
            sobot_tv_title.setText(title);
            sobot_tv_title.setVisibility(View.VISIBLE);
            for (int i = 0; i < dataList.size(); i++) {
                if (dataList.get(i) instanceof AlbumFile) {
                    AlbumFile albumFile = (AlbumFile) dataList.get(i);
                    View view = View.inflate(getContext(), R.layout.item_thumbnail_h, null);
                    ImageView thumbnail = view.findViewById(R.id.sobot_iv_album_content_image);
                    ImageView play = view.findViewById(R.id.sobot_iv_play_image);
                    SobotAlbum.getAlbumConfig().
                            getAlbumLoader().
                            load(thumbnail, albumFile);
                    int finalI = i;
                    thumbnail.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            setCurrentItem(finalI);
                        }
                    });
                    if (albumFile.getMediaType() == AlbumFile.TYPE_VIDEO) {
                        play.setVisibility(View.VISIBLE);
                    } else {
                        play.setVisibility(View.GONE);
                    }
                    sobot_thumbnail_ll.addView(view);
                }
            }
            scrollView.setVisibility(View.VISIBLE);
        }
        /*PreviewAdapter<Data> adapter = new PreviewAdapter<Data>(getContext(), dataList) {
            @Override
            protected void loadPreview(ImageView imageView, Data item, int position) {
                if (item instanceof String) {
                    Album.getAlbumConfig().getAlbumLoader().load(imageView, (String)item);
                } else if (item instanceof AlbumFile) {
                    Album.getAlbumConfig().getAlbumLoader().load(imageView, (AlbumFile)item);
                }
            }
        };
        adapter.setItemClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getPresenter().clickItem(mViewPager.getCurrentItem());
            }
        });
        adapter.setItemLongClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getPresenter().longClickItem(mViewPager.getCurrentItem());
            }
        });
        if (adapter.getCount() > 3) {
            mViewPager.setOffscreenPageLimit(3);
        } else if (adapter.getCount() > 2) {
            mViewPager.setOffscreenPageLimit(2);
        }
        mViewPager.setAdapter(adapter);*/
        fragments = new ArrayList<>();
        for (int i = 0; i < dataList.size(); i++) {
            if (dataList.get(i) instanceof AlbumFile) {
                AlbumFile albumFile = (AlbumFile) dataList.get(i);
                if (albumFile.getMediaType() == AlbumFile.TYPE_IMAGE) {
                    ImageFragment fragment = ImageFragment.getInstance(albumFile);
                    fragments.add(fragment);
                } else if (albumFile.getMediaType() == AlbumFile.TYPE_VIDEO) {
                    VideoFragment fragment = VideoFragment.getInstance(albumFile);
                    fragments.add(fragment);
                }
            }
        }
        pagerAdapter = new SobotViewPagerAdapter(mActivity, fragmentManager, fragments);
        mViewPager.setAdapter(pagerAdapter);
    }

    @Override
    public void setCurrentItem(int position) {
        mViewPager.setCurrentItem(position);
    }

    @Override
    public void setDurationDisplay(boolean display) {
        mTvDuration.setVisibility(display ? View.VISIBLE : View.GONE);
    }

    @Override
    public void setDuration(String duration) {
        mTvDuration.setText(duration);
    }

    @Override
    public void setChecked(boolean checked) {
        mCheckBox.setChecked(checked);
    }

    @Override
    public void setBottomDisplay(boolean display) {
        mLayoutBottom.setVisibility(display ? View.VISIBLE : View.GONE);
    }

    @Override
    public void setLayerDisplay(boolean display) {
//        mLayoutLayer.setVisibility(display ? View.VISIBLE : View.GONE);
    }

    @Override
    public void setCompleteText(String sCheckedCount) {
        String text = String.format(mActivity.getResources().getString(R.string.sobot_select_photo_num), sCheckedCount);
        SpannableStringBuilder ssp = new SpannableStringBuilder(text);
        ssp.setSpan(new ForegroundColorSpan(mActivity.getResources().getColor(R.color.sobot_color)), text.indexOf(sCheckedCount), text.indexOf(sCheckedCount) + sCheckedCount.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        sobot_tv_select.setText(ssp);
        try {
            selectCount = Integer.parseInt(sCheckedCount);
        } catch (Exception e) {
            selectCount = 0;
        }
        if (selectCount == 0) {
            sobot_tv_add.setBackgroundResource(R.drawable.sobot_bg_theme_unable_4dp);
        } else {
            sobot_tv_add.setBackgroundResource(R.drawable.sobot_bg_theme_color_4dp);
        }
    }

    @Override
    public void onClick(View v) {
        if (v == mCheckBox) {
            getPresenter().onCheckedChanged();
        } else if (v == mLayoutLayer) {
            // Intercept click events.
        } else if (v == sobot_tv_add) {
            if (selectCount > 0) {
                getPresenter().complete();
            }
        }
    }
}