package com.tech4fun.jesse.news.menudetailpager;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.tech4fun.jesse.news.R;
import com.tech4fun.jesse.news.activity.ShowImageActivity;
import com.tech4fun.jesse.news.base.BasePager;
import com.tech4fun.jesse.news.base.MenuDetailBasePager;
import com.tech4fun.jesse.news.domain.NewsCenterPagerBean;
import com.tech4fun.jesse.news.domain.PhotoDetailPagerBean;
import com.tech4fun.jesse.news.utils.CacheUtils;
import com.tech4fun.jesse.news.utils.Constants;
import com.tech4fun.jesse.news.utils.LogUtil;
import com.tech4fun.jesse.news.volley.VolleyManager;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.io.UnsupportedEncodingException;
import java.util.List;

import okhttp3.Call;

/**
 * Created by jesse on 17-4-26.
 */

public class PhotosMenuDetailPager extends MenuDetailBasePager {

    private boolean isShowListView = true;

    private final NewsCenterPagerBean.DataBean dataBean;
    @ViewInject(R.id.lv_photos)
    ListView lvPhotos;

    @ViewInject(R.id.gv_photos)
    GridView gvPhotos;
    private String url;
    private List<PhotoDetailPagerBean.DataBean.NewsBean> news;
    private MyBaseAdapter adapter;


    public PhotosMenuDetailPager(Context context, NewsCenterPagerBean.DataBean dataBean) {
        super(context);
        this.dataBean = dataBean;
    }

    @Override
    public View initView() {
        View view = View.inflate(context, R.layout.photos_menudetail_pager, null);
        x.view().inject(this, view);

        lvPhotos.setOnItemClickListener(new MyOnItemClickListener());
        gvPhotos.setOnItemClickListener(new MyOnItemClickListener());
        return view;
    }

    @Override
    public void initData() {
        super.initData();
        url = Constants.BASE_URL + dataBean.getUrl();
        String savedJson = CacheUtils.getString(context, url);
        if (!TextUtils.isEmpty(savedJson)){
            processData(savedJson);
        }
        //getDataFromNetByVolley();
        getDataFromNetByOkhttpUtils();
    }

    private void getDataFromNetByOkhttpUtils() {

        OkHttpUtils
                .get()
                .url(url)
                .id(100)
                .build()
                .execute(new MyStringCallback());
    }

    public class MyStringCallback extends StringCallback
    {
        @Override
        public void onBefore(okhttp3.Request request, int id)
        {

        }

        @Override
        public void onAfter(int id)
        {

        }

        @Override
        public void onError(Call call, Exception e, int id)
        {
            e.printStackTrace();
            LogUtil.e("使用okHttpUtils联网失败：" + e.getMessage());
        }

        @Override
        public void onResponse(String response, int id)
        {
            LogUtil.e("onResponse：complete");
            LogUtil.e("使用okHttpUtils联网成功：" + response);
            // 缓存数据
            CacheUtils.putString(context, url, response);
            processData(response);

            switch (id)
            {
                case 100:
                    Toast.makeText(context, "http", Toast.LENGTH_SHORT).show();
                    break;
                case 101:
                    Toast.makeText(context, "https", Toast.LENGTH_SHORT).show();
                    break;
            }
        }

        @Override
        public void inProgress(float progress, long total, int id)
        {
            LogUtil.e("inProgress:" + progress);

        }
    }

    private void processData(String json) {

        PhotoDetailPagerBean bean = parsedJson(json);
        isShowListView = true;
        news = bean.getData().getNews();

        adapter = new MyBaseAdapter();
        lvPhotos.setAdapter(adapter);
    }

    private PhotoDetailPagerBean parsedJson(String json) {
        return new Gson().fromJson(json, PhotoDetailPagerBean.class);
    }

    private void getDataFromNetByVolley() {

        StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String result) {
                LogUtil.e("使用volley联网成功：" + result);
                // 缓存数据
                CacheUtils.putString(context, url, result);
                processData(result);
            }

        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                LogUtil.e("使用volley联网失败：" + error.getMessage());
            }
        }){
            @Override
            protected Response<String> parseNetworkResponse(NetworkResponse response) {
                try {
                    String parsed = new String(response.data, "UTF-8");
                    return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                return super.parseNetworkResponse(response);
            }
        };

        VolleyManager.getRequestQueue().add(request);
    }

    public void switchListAndGrid(ImageButton ibSwitchListGrid) {
        if (isShowListView){
            isShowListView = false;
            gvPhotos.setVisibility(View.VISIBLE);
            adapter = new MyBaseAdapter();
            gvPhotos.setAdapter(adapter);
            lvPhotos.setVisibility(View.GONE);
            ibSwitchListGrid.setImageResource(R.drawable.icon_pic_list_type);
        }else {
            isShowListView = true;
            lvPhotos.setVisibility(View.VISIBLE);
            adapter = new MyBaseAdapter();
            lvPhotos.setAdapter(adapter);
            gvPhotos.setVisibility(View.GONE);
            ibSwitchListGrid.setImageResource(R.drawable.icon_pic_grid_type);
        }
    }

    private class MyBaseAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return news.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder;
            if (convertView == null){
                viewHolder = new ViewHolder();
                convertView = View.inflate(context, R.layout.item_photo_detail_pager, null);
                viewHolder.ivPhoto = (ImageView) convertView.findViewById(R.id.iv_photo);
                viewHolder.tvPhotoTitle = (TextView) convertView.findViewById(R.id.tv_photo_title);
                convertView.setTag(viewHolder);
            }else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            PhotoDetailPagerBean.DataBean.NewsBean newsBean = news.get(position);
            viewHolder.tvPhotoTitle.setText(newsBean.getTitle());
            String imageUrl = Constants.BASE_URL + newsBean.getSmallimage();
            loaderImager(viewHolder, imageUrl);
            return convertView;
        }
    }

    private void loaderImager(final ViewHolder viewHolder, String imageurl) {
        //设置tag
        viewHolder.ivPhoto.setTag(imageurl);
        //直接在这里请求会乱位置
        ImageLoader.ImageListener listener = new ImageLoader.ImageListener() {
            @Override
            public void onResponse(ImageLoader.ImageContainer imageContainer, boolean b) {
                if (imageContainer != null) {

                    if (viewHolder.ivPhoto != null) {
                        if (imageContainer.getBitmap() != null) {
                            //设置图片
                            viewHolder.ivPhoto.setImageBitmap(imageContainer.getBitmap());
                        } else {
                            //设置默认图片
                            viewHolder.ivPhoto.setImageResource(R.drawable.home_scroll_default);
                        }
                    }
                }
            }
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                //如果出错，则说明都不显示（简单处理），最好准备一张出错图片
                viewHolder.ivPhoto.setImageResource(R.drawable.home_scroll_default);
            }
        };
        VolleyManager.getImageLoader().get(imageurl, listener);
    }

    static class ViewHolder{
        ImageView ivPhoto;
        TextView tvPhotoTitle;
    }

    private class MyOnItemClickListener implements android.widget.AdapterView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            PhotoDetailPagerBean.DataBean.NewsBean newsBean = news.get(position);
            String imageUrl = Constants.BASE_URL + newsBean.getLargeimage();
            Intent intent = new Intent(context, ShowImageActivity.class);
            intent.putExtra("url", imageUrl);
            context.startActivity(intent);
        }
    }
}
