package ai.pai.client.activity;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;

import com.android.common.executors.ThreadExecutor;
import com.android.common.utils.DeviceUtils;
import com.android.common.utils.LogHelper;
import com.android.common.utils.NetworkUtil;

import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import ai.pai.client.R;
import ai.pai.client.db.Preferences;
import ai.pai.client.services.UpgradeService;
import ai.pai.client.utils.HttpPostTask;
import ai.pai.client.utils.UrlContainer;

public class WelcomeActivity extends BaseActivity {

    private Handler mHandler;
    private boolean isShowGuest;
    private static final int NORMAL_DELAY_TIME = 1500;
    private HttpPostTask checkGuestTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LogHelper.d(TAG,"czy onCreate"+hashCode());
        setContentView(R.layout.activity_welcome);
        mHandler = new Handler();
    }

    @Override
    protected void onResume() {
        super.onResume();
        LogHelper.d(TAG,"czy onResume");
        checkUpdateAndSplash();
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent intent ;
                if(Preferences.getInstance(getApplicationContext()).getNickName().isEmpty()){
                    intent = new Intent(WelcomeActivity.this, GuideActivity.class);
                    intent.putExtra("showGuest",isShowGuest);
                }else{
                    intent = new Intent(WelcomeActivity.this, MainActivity.class);
                }
                startActivity(intent);
                finish();
            }
        }, NORMAL_DELAY_TIME);
    }

    @Override
    protected void onStop() {
        super.onStop();
        mHandler.removeCallbacksAndMessages(null);
        if (checkGuestTask != null && checkGuestTask.getStatus() == AsyncTask.Status.RUNNING) {
            checkGuestTask.cancel(true);
            checkGuestTask = null;
        }
    }

    private void checkUpdateAndSplash() {
        if(Preferences.getInstance(getApplicationContext()).getNickName().isEmpty()){
            doCheckGuestStatus();
        }
        try {
            String curDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            LogHelper.d(TAG, "上次启动日期" + curDate);
            if (!Preferences.getInstance(this).getLastRunDate().equals(curDate) && NetworkUtil.isWifiConnected(this)) {
                LogHelper.d(TAG, "今日首次启动，且wifi环境，开始检查更新");
                Preferences.getInstance(this).setLastRunDate(curDate);
                Intent intent = new Intent(this, UpgradeService.class);
                startService(intent);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void doCheckGuestStatus( ) {
        if (checkGuestTask != null && checkGuestTask.getStatus() == AsyncTask.Status.RUNNING) {
            return;
        }
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("uuid", DeviceUtils.getUUID(this));
        checkGuestTask = new HttpPostTask(this, params) {

            @Override
            protected boolean parseResponse(Context context, String response) {
                try {
                    JSONObject json = new JSONObject(response);
                    int status = json.getInt("status");
                    if (status == 200) {
                        LogHelper.d(TAG, " doCheckGuestStatus parseResponse status ok");
                        return true;
                    }
                } catch (Exception e) {
                    LogHelper.d(TAG, " doCheckGuestStatus parseResponse error :" + e);
                }
                return false;
            }

            @Override
            protected void onPostFail(Context context) {
                super.onPostFail(context);
                isShowGuest = false;
            }

            @Override
            protected void onPostSuccess(Context context) {
                super.onPostSuccess(context);
                isShowGuest = true;
            }

        };
        checkGuestTask.executeOnExecutor(ThreadExecutor.getInstance().getExecutor(), UrlContainer.GUEST_STATUS_URL);
    }


}
