package jp.odakyu.toiletsignage.task;

import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONObject;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.TimerTask;

import jp.odakyu.toiletsignage.connection.ToiletServerConnection;
import jp.odakyu.toiletsignage.info.ToiletInfo;
import jp.odakyu.toiletsignage.json.ResultToiletJson;
import jp.odakyu.toiletsignage.json.ToiletDefaultJson;

import static java.lang.Boolean.FALSE;
import static java.lang.Boolean.TRUE;

/**
 * Created by agentec on 2017/12/11.
 */

public class UpdateToiletInfoTask extends TimerTask {
    private static int mErrorCount = 0;
    private final String TAG = "UpdateToiletInfoTask";
    private Context applicationContext;
    private ToiletInfo toiletInfo;

    public UpdateToiletInfoTask(Context context){
        applicationContext = context;
        toiletInfo = ToiletInfo.getInstance();
    }

    @Override
    public void run() {
        Log.i(TAG, "Thread Start");
        boolean isNetworkConnect = TRUE;
        //インターネット接続チェック
        if (isInternetAvailable() && isNetworkAvailable(applicationContext)) {
            ArrayList<ToiletDefaultJson> toiletInfoArray = toiletInfo.getToiletDefaultJsonArray();
            boolean isError = FALSE;
            for (ToiletDefaultJson toiletDefaultJson:toiletInfoArray) {
                ToiletServerConnection con = new ToiletServerConnection();
                try {
                    String jsonString = con.connectionToiletServer(toiletDefaultJson.getToiletId());
                    JSONObject jsonObject = new JSONObject(jsonString);
                    if (jsonObject == null) {
                        Log.e(TAG,"json object null jsonString = " + jsonString);
                        isError = TRUE;
                        break;
                    }

                    int code = jsonObject.getInt(ResultToiletJson.KEY_CODE);
                    if (code != 200000) {
                        Log.e(TAG,"response code error = " + code);
                        isError = TRUE;
                        break;
                    }

                    ArrayList<ResultToiletJson> resultToiletJsonArray = new ArrayList<ResultToiletJson>();
                    JSONArray jsonArray = jsonObject.getJSONArray(ResultToiletJson.KEY_RESULT);
                    for (int i = 0; i < jsonArray.length(); i++){
                        ResultToiletJson resultToiletJson = new ResultToiletJson((JSONObject) jsonArray.get(i));
                        resultToiletJsonArray.add(resultToiletJson);
                    }

                    ToiletInfo.getInstance().setResultToiletJsonMap(toiletDefaultJson.getToiletId(), resultToiletJsonArray);

                    if (jsonString == null) {
                        Log.e(TAG,"response json String null");
                        isError = TRUE;
                        break;
                    }

                    Log.d(TAG,"jsonString = " + jsonString);
                } catch (Exception e) {
                    e.printStackTrace();
                    String stackTrace = Log.getStackTraceString(e);
                    Log.e(TAG, stackTrace);
                    isError = TRUE;
                    break;
                }
            }
            if (isError) {
                mErrorCount++;
            } else {
                mErrorCount = 0;
            }
        } else {
            mErrorCount++;
            isNetworkConnect = FALSE;
        }

        toiletInfo.setConnectErrorCount(mErrorCount);
        toiletInfo.setNetworkConnect(isNetworkConnect);

        //Broadcast送信
        Intent intent = new Intent("jp.odakyu.toiletsignage.CONNECT_FINISH");
        applicationContext.sendBroadcast(intent);

        Log.d(TAG, "Thread End");
    }

    public boolean isNetworkAvailable(Context context) {
        final ConnectivityManager connectivityManager = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));
        return connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isConnected();
    }

    public boolean isInternetAvailable() {
        try {
            final InetAddress address = InetAddress.getByName("google.com");
            return !address.equals("");
        } catch (UnknownHostException e) {
            // Log error
            e.printStackTrace();
        }
        return false;
    }
}
