package com.ihaoin.hooloo.device.network;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.fasterxml.jackson.databind.JsonNode;
import com.ihaoin.hooloo.device.config.AppConfig;
import com.ihaoin.hooloo.device.util.JsonUtils;

import java.io.IOException;
import java.net.NetworkInterface;
import java.util.Collections;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class HttpUtil {
    private static final String TAG = "HL_Network";

    public static void post(String url, String body, Handler handler) {
        if (body == null) {
            body = "";
        }
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), body);
        Request request = new Request.Builder().url(url).post(requestBody).build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                HttpUtil.onFailure(handler, call, e);
            }

            @Override
            public void onResponse(Call call, Response response) {
                HttpUtil.onResponse(handler, call, response);
            }
        });
    }

    public static void get(String url, Handler handler) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).get().build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                HttpUtil.onFailure(handler, call, e);
            }

            @Override
            public void onResponse(Call call, Response response) {
                HttpUtil.onResponse(handler, call, response);
            }
        });
    }

    private static void onFailure(Handler handler, Call call, Exception e) {
        try {
            if (handler == null) {
                String msgText = String.format("请求:%s, 返回状态:%s, 返回内容:%s", call.request().url(), 0, e.getMessage());
                Log.e(TAG, msgText);
                return;
            }
            sendHandlerMessage(0, handler, call, e);
        } catch (Exception ex) {
            onFailure(handler, call, e);
        }
    }

    private static void onResponse(Handler handler, Call call, Response response) {
        try {
            String responseBody = response.body().string();
            JsonNode jsonObject = JsonUtils.getMapper().readValue(responseBody, JsonNode.class);
            if (jsonObject == null) {
                onFailure(handler, call, new BizException("返回body为空"));
                return;
            }
            if (jsonObject.get("code").asInt() != 200) {
                onFailure(handler, call, new BizException(jsonObject.get("msg").asText()));
                return;
            }
            if (handler == null) {
                String msgText = String.format("请求:%s, 返回状态:%s, 返回内容:%s", call.request().url(), 1, responseBody);
                Log.i(TAG, msgText);
                return;
            }
            sendHandlerMessage(1, handler, call, jsonObject.get("data") == null ? "" : jsonObject.get("data").toString());
        } catch (Exception e) {
            onFailure(handler, call, e);
        }
    }

    private static void sendHandlerMessage(Integer what, Handler handler, Call call, Object o) {
        Message msg = handler.obtainMessage(what, o);
        Bundle bundle = new Bundle();
        bundle.putString("url", call.request().url().toString());
        msg.setData(bundle);
        handler.sendMessage(msg);
    }

    public static void getMainDatas(Handler handler) {
        String url = String.format(HttpParams.GET_MAIN_DATA, AppConfig.MACHINE_CODE);
        get(url, handler);
    }

    public static void getOrders(Handler handler) {
        String url = String.format(HttpParams.GET_ORDERS, AppConfig.MACHINE_CODE);
        get(url, handler);
    }

    public static void postConfirmOrder(String body, Handler handler) {
        String url = String.format(HttpParams.POST_CONFIRM_ORDER, AppConfig.MACHINE_CODE);
        post(url, body, handler);
    }

    public static void postRegistrationId(String registrationId, Handler handler) {
        String url = String.format(HttpParams.POST_REGISTRATION_ID, AppConfig.MACHINE_CODE, registrationId);
        get(url, handler);
    }

    public static void checkSku(Integer skuId, Handler handler) {
        String url = String.format(HttpParams.CHECK_SKU, AppConfig.MACHINE_CODE, skuId);
        get(url, handler);
    }

    public static String getMacAddress() {
        try {
            if (AppConfig.DEBUG) {
                return "SN0091290001";
            }
            List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface nif : all) {
                if (!nif.getName().equalsIgnoreCase("wlan0")) continue;
                byte[] macBytes = nif.getHardwareAddress();
                if (macBytes == null) {
                    return null;
                }
                StringBuilder res1 = new StringBuilder();
                for (byte b : macBytes) {
                    res1.append(String.format("%02X:", b));
                }
                if (res1.length() > 0) {
                    res1.deleteCharAt(res1.length() - 1);
                }
                return res1.toString();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }
}
