package ai.pai.lensman.splash;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;

import com.android.common.utils.NetworkUtil;

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

import ai.pai.lensman.R;
import ai.pai.lensman.db.Preferences;
import ai.pai.lensman.login.LoginActivity;
import ai.pai.lensman.service.UpgradeService;
import ai.pai.lensman.upload.UploadActivity;

public class SplashActivity extends FragmentActivity {

    private Handler mHandler;
    private static final int NORMAL_DELAY_TIME = 1500;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        mHandler = new Handler();
    }

    @Override
    protected void onResume() {
        super.onResume();
        checkUpdateAndSplash();
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent intent ;
                if(Preferences.getInstance(getApplicationContext()).getLensManId().isEmpty()){
                    intent = new Intent(SplashActivity.this, LoginActivity.class);
                }else{
                    intent = new Intent(SplashActivity.this, UploadActivity.class);
                }
                startActivity(intent);
                finish();
            }
        }, NORMAL_DELAY_TIME);
    }

    @Override
    protected void onStop() {
        super.onStop();
        mHandler.removeCallbacksAndMessages(null);
    }

    private void checkUpdateAndSplash() {
        try {
            String curDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            if (!Preferences.getInstance(this).getLastRunDate().equals(curDate) && NetworkUtil.isWifiConnected(this)) {
                Preferences.getInstance(this).setLastRunDate(curDate);
                Intent intent = new Intent(this, UpgradeService.class);
                startService(intent);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
