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;

/**
 * 1.把数据从inputStream里面拿出来
 * 2.转为应用层想要的类型  然后回调给应用层
 */
public class JasonCallbackImpl<M> implements JasonCallbackListener {
    private Class<M> clazz;
    private IJasonListener iJasonListener;
    private Handler handler = new Handler(Looper.getMainLooper());

    public JasonCallbackImpl(Class<M> clazz, IJasonListener iJasonListener){
        this.clazz = clazz;
        this.iJasonListener = iJasonListener;
    }


    @Override
    public void onSuccess(InputStream inputStream) {
        //解析inputStream
        String jasonStr = getContent(inputStream);
        final M m = JSON.parseObject(jasonStr, clazz);
        handler.post(new Runnable() {
            @Override
            public void run() {
                iJasonListener.onSuccess(m);
            }
        });

    }

    @Override
    public void onFaild() {
        handler.post(new Runnable() {
            @Override
            public void run() {
                iJasonListener.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","");
    }

    public IJasonListener getiJasonListener() {
        return iJasonListener;
    }
}
