package com.maniu.http;

import android.os.Handler;
import android.os.Looper;

import com.alibaba.fastjson.JSON;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.logging.LogRecord;

/**
 * 内部回调接口的实现类
 * 用来将服务器返回的流转为用户想要的类型
 */
public class JasonCallBackImpl<M> implements CallBackListenner {
    //用户对这个接口的返回参数的需求
    private Class<M> response;
    //应用层的回调接口
    private IJsonListenner iJsonListenner;
    private Handler handler = new Handler(Looper.getMainLooper());


    public JasonCallBackImpl(Class<M> response, IJsonListenner iJsonListenner) {
        this.response = response;
        this.iJsonListenner = iJsonListenner;
    }

    @Override
    public void onSuccess(InputStream inputStream) {
        //首先  将数据从inputStream中拿出来
        String jsonStr = getContent(inputStream);
        final M m = JSON.parseObject(jsonStr, response);
        //先把线程切换到主线程
        handler.post(new Runnable() {
            @Override
            public void run() {
                iJsonListenner.onSuccess(m);
                //将数据进行缓存
            }
        });

    }

    @Override
    public void onFaild() {
        handler.post(new Runnable() {
            @Override
            public void run() {
                iJsonListenner.onFaild();
            }
        });
    }


    /**
     * inputStream转为String类型
     * @param inputStream
     * @return
     */
    private String getContent(InputStream inputStream) {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder sb = new StringBuilder();
        String line = null;
        try {
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line + "/n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString().replace("/n","");
    }
}
