package com.gh.gamecenter;

import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.RelativeLayout;

import com.gc.materialdesign.views.ProgressBarCircularIndeterminate;
import com.gh.base.BaseActivity;
import com.gh.common.util.DisplayUtils;
import com.gh.common.util.ImageUtils;
import com.gh.common.view.Gh_RelativeLayout;
import com.gh.common.view.Gh_RelativeLayout.OnSingleTapListener;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import pl.droidsonroids.gif.GifDrawable;
import pl.droidsonroids.gif.GifImageView;


/**
 * 查看游戏截图页面
 *
 * @author 黄壮华
 */
public class ViewImageActivity extends BaseActivity implements
        OnPageChangeListener {

    private ViewPager viewimage_vp_show;
    private ViewImageAdapter adapter;
    private View viewimage_slide_line;
    private RelativeLayout.LayoutParams rparams;

    private ArrayList<String> urls;

    private String scaleType;

    private int width;

    private boolean isOrientation;
    private boolean isLoading = false;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            notifyItemChanged(msg.arg1);
        }
    };

    private void notifyItemChanged(int position) {
        Object object = viewimage_vp_show.findViewWithTag(position);
        if (object != null) {
            RelativeLayout view = (RelativeLayout) object;
            ImageView imageView = (ImageView) view.findViewById(R.id.viewimage_iv_show);
            final ProgressBarCircularIndeterminate progressBar = (ProgressBarCircularIndeterminate) view.findViewById(R.id.viewimage_pb_loading);
            progressBar.setVisibility(View.VISIBLE);
            if (scaleType != null) {
                ImageUtils.getInstance(getApplicationContext()).display(
                        urls.get(position), imageView, ScaleType.FIT_CENTER,
                        new ImageUtils.OnLoadingCompleteListener() {
                            @Override
                            public void onLoadingComplete() {
                                progressBar.setVisibility(View.GONE);
                            }
                        });
            } else {
                ImageUtils.getInstance(getApplicationContext()).display(
                        urls.get(position), imageView, new ImageUtils.OnLoadingCompleteListener() {
                            @Override
                            public void onLoadingComplete() {
                                progressBar.setVisibility(View.GONE);
                            }
                        });
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent intent = getIntent();
        urls = intent.getStringArrayListExtra("urls");
        int current = intent.getIntExtra("current", 0);
        scaleType = intent.getStringExtra("ScaleType");

        if (savedInstanceState != null) {
            current = savedInstanceState.getInt("currentItem", 0);
            isOrientation = savedInstanceState.getBoolean("isOrientation");
        }

        setContentView(R.layout.activity_viewimage);

        DisplayMetrics outMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
        width = outMetrics.widthPixels / urls.size();

        rparams = new RelativeLayout.LayoutParams(width, DisplayUtils.dip2px(
                getApplicationContext(), 1));
        rparams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        rparams.bottomMargin = DisplayUtils.dip2px(getApplicationContext(), 10);
        rparams.leftMargin = width * current;
        viewimage_slide_line = findViewById(R.id.viewimage_slide_line);
        viewimage_slide_line.setLayoutParams(rparams);

        viewimage_vp_show = (ViewPager) findViewById(R.id.viewimage_vp_show);
        adapter = new ViewImageAdapter();
        viewimage_vp_show.setAdapter(adapter);
        viewimage_vp_show.setCurrentItem(current);
        viewimage_vp_show.addOnPageChangeListener(this);

        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            isOrientation = true; // 横屏
        } else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            isOrientation = false;// 竖屏
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("currentItem", viewimage_vp_show.getCurrentItem());
        outState.putBoolean("isOrientation", isOrientation);
    }

    private class ViewImageAdapter extends PagerAdapter implements
            OnSingleTapListener {

        @Override
        public int getCount() {
            if (urls == null) {
                return 0;
            }
            return urls.size();
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            String url = urls.get(position);
            Gh_RelativeLayout view;
            if (url.contains(".gif")) {
                view = (Gh_RelativeLayout) View.inflate(container.getContext(),
                        R.layout.viewimage_gif_item, null);
                GifImageView gifImageView = (GifImageView) view.findViewById(R.id.viewimage_iv_gif);
                if (!isLoading) {
                    loadGifData(gifImageView, urls.get(position));
                }

            } else {
                view = (Gh_RelativeLayout) View.inflate(container.getContext(),
                        R.layout.viewimage_normal_item, null);
                ImageView imageView = (ImageView) view.findViewById(R.id.viewimage_iv_show);
                if (scaleType != null) {
                    ImageUtils.getInstance(getApplicationContext()).display(
                            urls.get(position), imageView, ScaleType.FIT_CENTER);
                } else if (isOrientation && imageView.getDrawable() == null) {
                    ImageUtils.getInstance(getApplicationContext()).display(
                            urls.get(position), imageView, 270, isOrientation);
                } else if (imageView.getDrawable() == null) {
                    ImageUtils.getInstance(getApplicationContext()).display(
                            urls.get(position), imageView);
                }
                if (!urls.get(position).startsWith("http://image.ghzhushou.com/pic/hq/")) {
                    checkUrl(urls.get(position));
                }
            }
            view.setOnSingleTapListener(this);
            view.setTag(position);
            container.addView(view);
            return view;
        }

        private void loadGifData(final GifImageView gifImageView, final String gifUrl) {
            isLoading = true;
            gifImageView.setImageResource(R.drawable.ocupy);
            gifImageView.setScaleType(ScaleType.CENTER);
            final GifDrawable[] gifDrawable = {null};
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        URL url = new URL(gifUrl);
                        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                        conn.setRequestMethod("GET");
                        conn.setConnectTimeout(5 * 1000);
                        conn.setReadTimeout(5 * 1000);
                        conn.connect();
                        if (conn.getResponseCode() == 200) {
                            InputStream inputStream = conn.getInputStream();
                            ByteArrayOutputStream output = new ByteArrayOutputStream();
                            byte[] data = new byte[1024 * 5];
                            int count = -1;
                            while ((count = inputStream.read(data, 0, 1024 * 5)) != -1) {
                                output.write(data, 0, count);
                            }
                            byte[] bytes = output.toByteArray();
                            gifDrawable[0] = new GifDrawable(bytes);
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    gifImageView.setImageDrawable(gifDrawable[0]);
                                    gifImageView.setScaleType(ScaleType.FIT_CENTER);
                                }
                            });
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

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

        @Override
        public void onSingleTap() {
            finish();
        }

    }

    @Override
    public void onPageScrollStateChanged(int newState) {

    }

    @Override
    public void onPageScrolled(int position, float positionOffset,
                               int positionOffsetPixels) {
        if (positionOffset != 0) {
            rparams.leftMargin = (int) (width * (positionOffset + position));
            viewimage_slide_line.setLayoutParams(rparams);
        }
    }

    @Override
    public void onPageSelected(int position) {

    }

    private void checkUrl(final String url) {
        if (!url.startsWith("http://image.ghzhushou.com/pic/")) {
            return;
        }
        new Thread() {
            @Override
            public void run() {
                try {
                    String newUrl = "http://image.ghzhushou.com/pic/hq" + url.substring(url.lastIndexOf("/"));
                    HttpURLConnection connection = (HttpURLConnection) new URL(newUrl).openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(5 * 1000);
                    connection.setReadTimeout(5 * 1000);
                    connection.connect();
                    int code = connection.getResponseCode();
                    if (code == 200) {
                        //图片存在
                        if (urls == null) {
                            return;
                        }
                        //urls出现空指针
                        for (int i = 0, size = urls.size(); i < size; i++) {
                            if (urls.get(i).equals(url)) {
                                urls.set(i, newUrl);
                                Message msg = new Message();
                                msg.arg1 = i;
                                handler.sendMessage(msg);
                                break;
                            }
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        viewimage_vp_show = null;
        adapter = null;
        viewimage_slide_line = null;
        rparams = null;
        urls = null;
        System.gc();
    }
}
