package com.bokecc.dwlivedemo.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.bokecc.dwlivedemo.R;
import com.bumptech.glide.Glide;
import com.github.chrisbanes.photoview.PhotoView;

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

public class ImageDetailsActivity extends AppCompatActivity {


    public static final int RESULT_CODE = 10057;
    public static final int REQUEST_CODE = 10056;
    private ArrayList<String> list;
    private ArrayList<String> sourceList = new ArrayList<>();
    private RelativeLayout rlImageDetailsTitleBar;
    private ImageView ivImageDetailsDelete;
    private PagerAdapter pagerAdapter;
    private ViewPager viewPager;
    private TextView tvImageDetailsTitleNumber;

    private List<Integer> deleteList = new ArrayList<>();
    private int index = 0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
//        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
//                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.image_details_activity);

        setColor(Color.TRANSPARENT);

        String imageUrl = getIntent().getStringExtra("imageUrl");
        boolean hasDelete = getIntent().getBooleanExtra("hasDelete",false);
        index = getIntent().getIntExtra("index",0);

        if (TextUtils.isEmpty(imageUrl)){
            finish();
            return;
        }


        rlImageDetailsTitleBar = findViewById(R.id.rl_image_details_title_bar);
        tvImageDetailsTitleNumber = findViewById(R.id.tv_image_details_title_number);

        rlImageDetailsTitleBar.setPadding(0, (int) getStatusBarHeight(),0,0);

        ivImageDetailsDelete = findViewById(R.id.iv_image_details_delete);
        list = new ArrayList<>(Arrays.asList(imageUrl.split("###")));
        sourceList.addAll(list);
//        tvImageDetailsTitleNumber.setText("1/"+(list.size()));
        if (hasDelete){
            ivImageDetailsDelete.setVisibility(View.VISIBLE);
            ivImageDetailsDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    deleteCurrentImage();
                }
            });
        }


        viewPager = findViewById(R.id.vp_image_details);

        initViewPager();

        if (index<list.size()){
            try{
                viewPager.setCurrentItem(index);
            }catch (Exception e){
                 e.printStackTrace();
            }
        }


        findViewById(R.id.iv_image_details_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                close();
            }
        });

    }

    private void close() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < deleteList.size(); i++) {
            int position = deleteList.get(i);
            sb.append(""+position);
            if (i<deleteList.size()-1){
                sb.append(",");
            }
        }
        Intent intent = new Intent();
        intent.putExtra("delete",sb.toString());
        setResult(RESULT_CODE,intent);
        finish();
    }

    private void deleteCurrentImage() {
        if (deleteList!=null){
            int currentIndex = viewPager.getCurrentItem();
            if (list.size()<=currentIndex){
                return;
            }
            String url = list.get(currentIndex);
            list.remove(currentIndex);
            deleteList.add(sourceList.indexOf(url));
            if (list.size()==0){
                close();
            }else {
                initViewPager();
                //如果currentIndex不是最后一张，显示下一张图片
                if (currentIndex<list.size()){
                    viewPager.setCurrentItem(currentIndex);
                }else {
                    viewPager.setCurrentItem(list.size()-1);
                    tvImageDetailsTitleNumber.setText(list.size()+"/"+(list.size()));
                }
            }
        }
    }


    private void initViewPager(){
        pagerAdapter = new PagerAdapter() {
            @Override
            public int getCount() {
                return list.size();
            }

            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                View view = View.inflate(ImageDetailsActivity.this,R.layout.image_details_item_view,null);
                PhotoView photoView = view.findViewById(R.id.photo_view);
                String url = list.get(position);
                if (!TextUtils.isEmpty(url)){
                    Glide.with(ImageDetailsActivity.this).load(url).into(photoView);
                }
                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                });

                container.addView(view);
                return view;
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                if (object instanceof View){
                    container.removeView((View) object);
                }
            }

            @Override
            public boolean isViewFromObject(View view, Object object) {
                return view == object;
            }
        };
        viewPager.setAdapter(pagerAdapter);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                tvImageDetailsTitleNumber.setText((position+1)+"/"+(list.size()));
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode==KeyEvent.KEYCODE_BACK){
            close();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void setColor(int color){
        if (Build.VERSION.SDK_INT >= 21) {
            View view = getWindow().getDecorView();
            view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(color);
        }
    }

    private double getStatusBarHeight(){
        return Math.ceil(25 * getResources().getDisplayMetrics().density);

    }
}
