package com.lee.network.volley;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.lee.base.activity.BaseActivity;
import com.lee.network.R;
import com.noobyang.log.LogUtil;

import org.json.JSONObject;

/**
 * Volley Activity
 * 在2013年Google I/O大会上推出了一个新的网络通信框架Volley。
 * Volley既可以访问网络取得数据，也可以加载图片，并且在性能方面也进行了大幅度的调整;
 * 它的设计目标就是非常适合去进行数据量不大，但通信频繁的网络操作;
 * 而对于大数据量的网络操作，比如说下载文件等，Volley的表现就会非常糟糕。
 * 在使用Volley前请下载Volley库并放在libs目录下并add到工程中。
 * </p>
 * Created by LiYang on 2017/7/28.
 */

public class VolleyActivity extends BaseActivity {

    private NetworkImageView ivNetworkImageView;
    private ImageView ivResult;
    private TextView tvResult;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_vollery);
        findViewById(R.id.btn_volley_string).setOnClickListener(clickListener);
        findViewById(R.id.btn_volley_json).setOnClickListener(clickListener);
        findViewById(R.id.btn_volley_image).setOnClickListener(clickListener);
        findViewById(R.id.btn_volley_net_image_view).setOnClickListener(clickListener);
        ivNetworkImageView = (NetworkImageView)findViewById(R.id.iv_network_image_view);
        ivResult = (ImageView)findViewById(R.id.iv_volley_result);
        tvResult = (TextView)findViewById(R.id.tv_volley_result);
    }

    private View.OnClickListener clickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            tvResult.setText("");
            if(v.getId() == R.id.btn_volley_string) {
                dealRequestString();
            } else if (v.getId() == R.id.btn_volley_json) {
                dealRequestJson();
            } else if (v.getId() == R.id.btn_volley_image) {
                dealRequestImage();
            } else if (v.getId() == R.id.btn_volley_net_image_view) {
                dealNetImageView();
            }
        }
    };

    private void dealRequestString() {
        RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
        StringRequest stringRequest = new StringRequest(Request.Method.GET, "https://juejin.im",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        LogUtil.d("dealRequestString onResponse");
                        Message message = uiHandler.obtainMessage();
                        message.arg1 = 200;
                        message.obj = s;
                        uiHandler.sendMessage(message);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        LogUtil.d("dealRequestString onErrorResponse");
                        Message message = uiHandler.obtainMessage();
                        message.arg1 = volleyError.networkResponse.statusCode;
                        uiHandler.sendMessage(message);
                    }
                });
        queue.add(stringRequest);
    }

    private void dealRequestJson() {
        RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
        JSONObject jsonObject = new JSONObject();
        jsonObject.optString("username", "lee");
        jsonObject.optString("password", "123");
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
                "https://juejin.im", jsonObject,
                new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        LogUtil.d("dealRequestJson onResponse");
                        Message message = uiHandler.obtainMessage();
                        message.arg1 = 200;
                        message.obj = jsonObject.toString();
                        uiHandler.sendMessage(message);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        LogUtil.d("dealRequestJson onErrorResponse");
                        Message message = uiHandler.obtainMessage();
                        message.arg1 = volleyError.networkResponse.statusCode;
                        uiHandler.sendMessage(message);
                    }
                });
        queue.add(jsonObjectRequest);
    }

    private void dealRequestImage() {
        RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
        ImageRequest imageRequest = new ImageRequest(
                "https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/logo_white_fe6da1ec.png",
                new Response.Listener<Bitmap>() {
                    @Override
                    public void onResponse(Bitmap response) {
                        LogUtil.d("dealRequestJson onResponse");
                        ivResult.setImageBitmap(response);
                    }
                }, 0, 0, Bitmap.Config.RGB_565, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        LogUtil.d("dealRequestImage onErrorResponse");
                    }
                });
        queue.add(imageRequest);
    }

    private void dealNetImageView() {
        RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
        ImageLoader imageLoader = new ImageLoader(queue, new ImageLoader.ImageCache() {
            @Override
            public Bitmap getBitmap(String s) {
                return null;
            }

            @Override
            public void putBitmap(String s, Bitmap bitmap) {

            }
        });
        ivNetworkImageView.setImageUrl("https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/logo_white_fe6da1ec.png",
                imageLoader);
    }

    @SuppressLint("HandlerLeak")
    private Handler uiHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            tvResult.setText("StatusCode = " + msg.arg1 + "\n" + "Content = " + msg.obj);
        }
    };

}
