package com.danding.yang800.Presenter;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
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.HttpHeaderParser;
import com.android.volley.toolbox.StringRequest;
import com.danding.yang800.BuildConfig;
import com.danding.yang800.General.HttpCallBack;
import com.danding.yang800.General.SingleRequestQueue;
import com.danding.yang800.General.Yang800App;
import com.danding.yang800.LogoActivity;
import com.danding.yang800.Service.LoginKeepService;
import com.danding.yang800.Util.VolleyUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class LogoActivityPresenter {
    private LogoActivity context;
    SharedPreferences sp;
    RequestQueue requestQueue;

    public LogoActivityPresenter(LogoActivity context) {
        sp = context.getSharedPreferences("variable", Context.MODE_PRIVATE);
        this.context = context;
        requestQueue = SingleRequestQueue.getRequestQueue(context);
    }

    public void keepLogin() {
        HashMap<String, String> map = new HashMap<>();
        new VolleyUtil(context).request(context, "login.loginHold", false, map, new HttpCallBack() {
            @Override
            public void onSuccess(JSONObject json) {

                try {
                    int userId=sp.getInt("userId", 0);
                    context.isLogin = true;
                    if (!isWorked("com.danding.yang800.Service.LoginKeepService")) {
                        Intent startIntent = new Intent(
                                context,
                                LoginKeepService.class);
                        context.startService(startIntent);
                    }
                } catch (Exception e) {
                    tokenLogin();
                }
            }

            @Override
            public void onerrSuccess() {
                tokenLogin();
            }

            @Override
            public void onCatch() {

            }

            @Override
            public void onFail() {
            }
        });


    }

//    String rawCookies = "";
//
//    public void keepLogin() {
//        StringRequest stringRequest = new StringRequest(Request.Method.POST,
//                "http://" + BuildConfig.HOSTURL + "/xhr/login/loginHold.json",
//                new Response.Listener<String>() {
//                    @Override
//                    public void onResponse(String response) {
//                        // ToastUtil.show(context, response);
//                        try {
//                            JSONObject json = new JSONObject(response);
//                            String code = json.getString("code");
//                            if (!code.equals("success")) {
//                                sp.edit().putString("Cookie", rawCookies).commit();
//                                tokenLogin();
//                            } else {
//                                context.isLogin = true;
//                                if (!isWorked("com.danding.yang800.Service.LoginKeepService")) {
//                                    Intent startIntent = new Intent(
//                                            context,
//                                            LoginKeepService.class);
//                                    context.startService(startIntent);
//                                }
//                            }
//                        } catch (JSONException e) {
//                            e.printStackTrace();
//                        }
//
//
//                    }
//                }, new Response.ErrorListener() {
//
//            @Override
//            public void onErrorResponse(VolleyError error) {
//            }
//        }) {
//            @Override
//            protected Response<String> parseNetworkResponse(
//                    NetworkResponse response) {
//                try {
//                    Map<String, String> responseHeaders = response.headers;
//                    rawCookies = responseHeaders.get("Set-Cookie");
////                    if (rawCookies.length() > 0) {
////                        String[] splitCookie = rawCookies.split(";");
////                        String[] splitSessionId = splitCookie[0].split("=");
////                        String cookie = splitSessionId[1];
////                        sp.edit().putString("Cookie", cookie).commit();
////                    }
//                    String dataString = new String(response.data, "UTF-8");
//                    return Response.success(dataString,
//                            HttpHeaderParser.parseCacheHeaders(response));
//                } catch (UnsupportedEncodingException e) {
//                    return Response.error(new ParseError(e));
//                }
//            }
//
//            @Override
//            public Map<String, String> getHeaders() throws AuthFailureError {
//                if (!sp.getString("Cookie", "").equals("")) {
//                    HashMap<String, String> headers = new HashMap<String, String>();
//                    headers.put("Cookie", sp.getString("Cookie", ""));
//                    return headers;
//                } else {
//                    return super.getHeaders();
//                }
//            }
//        };
//        stringRequest.setTag("POST_TAG");
//        requestQueue.add(stringRequest);
//    }

    public void tokenLogin() {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("token", sp.getString("token", ""));
        map.put("epCode", sp.getString("epCode", ""));
        new VolleyUtil(context).request(context, "login.tokenLogin", false, map, new HttpCallBack() {
            @Override
            public void onSuccess(JSONObject json) {
                try {
                    JSONObject jsondata = json.getJSONObject("result");
                    JSONObject jsonUser = jsondata.getJSONObject("user");
                    int userId = jsonUser.getInt("userId");
                    sp.edit().putInt("userId", userId).commit();
                    String token = jsonUser.getString("token");
                    sp.edit().putString("token", token).commit();
                    JSONObject jsonStore = jsondata.getJSONObject("store");
                    String storeId = jsonStore.getString("id");
                    sp.edit().putString("storeId", storeId).commit();
                    context.isLogin = true;
                    if (!isWorked("com.danding.yang800.Service.LoginKeepService")) {
                        Intent startIntent = new Intent(
                                context,
                                LoginKeepService.class);
                        context.startService(startIntent);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onerrSuccess() {
                sp.edit().putBoolean("login", false).commit();
            }

            @Override
            public void onCatch() {

            }

            @Override
            public void onFail() {
            }
        });
//        StringRequest stringRequest = new StringRequest(Request.Method.POST,
//                "http://" + BuildConfig.HOSTURL + "/xhr/login/tokenLogin.json",
//                new Response.Listener<String>() {
//                    @Override
//                    public void onResponse(String response) {
//                        // ToastUtil.show(context, response);
//                        Log.d("LoginActivity", response);
//                        Log.d("LoginActivity", sp.getString("Cookie", ""));
//                        // ToastUtil.show(LoginKeepService.this, response);
//                        try {
//                            JSONObject json = new JSONObject(response);
//                            String code = json.getString("code");
//                            if (!code.equals("success")) {
//                                sp.edit().putBoolean("login", false).commit();
//                                //sp.edit().putString("WXcode", "").commit();
//                            } else {
//                                JSONObject jsondata = json.getJSONObject("data");
//                                JSONObject jsonUser = jsondata.getJSONObject("user");
//                                String userId = jsonUser.getString("userId");
//                                sp.edit().putString("userId", userId).commit();
//                                String token = jsonUser.getString("token");
//                                sp.edit().putString("token", token).commit();
//                                JSONObject jsonStore = jsondata.getJSONObject("store");
//                                String storeId = jsonStore.getString("id");
//                                sp.edit().putString("storeId", storeId).commit();
//                                context.isLogin = true;
//                                if (!isWorked("com.danding.yang800.Service.LoginKeepService")) {
//                                    Intent startIntent = new Intent(
//                                            context,
//                                            LoginKeepService.class);
//                                    context.startService(startIntent);
//                                }
//                            }
//                        } catch (JSONException e) {
//                            e.printStackTrace();
//                        }
//
//
//                    }
//                }, new Response.ErrorListener() {
//
//            @Override
//            public void onErrorResponse(VolleyError error) {
//            }
//        }) {
//            @Override
//            protected HashMap<String, String> getParams() { //
//                HashMap<String, String> map = new HashMap<String, String>();
//                map.put("token", sp.getString("token", ""));
//                map.put("epCode", sp.getString("epCode", ""));
//                return map;
//            }
//
//
//            @Override
//            public Map<String, String> getHeaders() throws AuthFailureError {
//                HashMap<String, String> headers = new HashMap<String, String>();
//                headers.put("Cookie", sp.getString("Cookie", ""));
//                return headers;
//            }
//        };
//        stringRequest.setTag("POST_TAG");
//        requestQueue.add(stringRequest);
    }

    private boolean isWorked(String className) {
        ActivityManager myManager = (ActivityManager) context
                .getApplicationContext().getSystemService(
                        context.ACTIVITY_SERVICE);
        ArrayList<ActivityManager.RunningServiceInfo> runningService = (ArrayList<ActivityManager.RunningServiceInfo>) myManager
                .getRunningServices(300);
        for (int i = 0; i < runningService.size(); i++) {
            if (runningService.get(i).service.getClassName().toString()
                    .equals(className)) {
                return true;
            }
        }
        return false;
    }

}