package kr.co.zumo.app.lifeplus.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.schedulers.Schedulers;
import kr.co.zumo.app.R;
import kr.co.zumo.app.lifeplus.application.App;
import kr.co.zumo.app.lifeplus.model.LifeplusPreferences;
import kr.co.zumo.app.lifeplus.model.SuperModel;
import kr.co.zumo.app.lifeplus.model.SuperModelInit;
import kr.co.zumo.app.lifeplus.network.NetworkWatcher;
import kr.co.zumo.app.lifeplus.supervisor.DialogHelper;
import kr.co.zumo.app.lifeplus.util.AppUtil;
import kr.co.zumo.app.lifeplus.util.PermissionUtil;
import kr.co.zumo.app.lifeplus.util.StringUtil;
import kr.co.zumo.app.lifeplus.view.Event;
import kr.co.zumo.app.lifeplus.view.dialog.AlertDialog;
import kr.co.zumo.app.lifeplus.view.dialog.DialogBase;
import kr.co.zumo.app.lifeplus.view.dialog.DialogBuilder;
import kr.co.zumo.app.lifeplus.view.dialog.DialogID;
import kr.co.zumo.app.lifeplus.view.dialog.IAttribute;
import kr.co.zumo.app.lifeplus.view.dialog.IDialogResultListener;

/**
 * Splash 화면
 * <pre>
 * Splash 화면, manifests 에서 설정한 Theme 로 splash 화면이 구성된다.
 * </pre>
 *
 * @author 하세미
 * @version 1.0
 * @history 하세미   [2018-09-07]   [최초 작성]
 */
public class SplashActivity extends AppCompatActivity {

  CompositeDisposable disposable = new CompositeDisposable();

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    DialogHelper.getInstance().setFragmentManager(getSupportFragmentManager());
    Context context = App.getInstance().getContext();
    SuperModelInit.init(context);

    if (AppUtil.isRelease()) {
      disposable.add(NetworkWatcher.check(context)
        .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
        .subscribe(isConnected -> {
          disposable.dispose();

          launch(isConnected);
        }, Throwable::printStackTrace)
      );
    }
    else {
      launch(true);
    }
  }

  private void launch(Boolean isConnected) {
    Log.i("APP# SplashActivity | onCreate", "| Network Connected ==============================================================> " + isConnected);
    LifeplusPreferences preferences = SuperModel.getInstance().getPreferences();
    Intent intent;
    intent = new Intent(this, MainActivity.class);
    if (isConnected == false) {
      // intent = new Intent(this, NetworkErrorActivity.class);
    }
    else if (false) {
      // todo 앱 권한 안내 표시, 표시 후 권한 요청;
    }
    else if (preferences.isTutorialDone() == false) {
      intent = new Intent(this, TutorialActivity.class);
    }
    else if (StringUtil.isFull(SuperModel.getInstance().getUserId()) == false) {
      // todo 가입 안했음
      // 처음 사용자와 업데이트 사용자 구분

      // 업데이트 사용자
      if (StringUtil.isFull(preferences.getEncryptionUserNo())) {
        // todo 앱 업데이트 한 사람일 경우
        intent = new Intent(this, SignUpZumoUserActivity.class);
      }
      else { // 처음 사용자
        intent = new Intent(this, SignUpActivity.class);
      }
    }

    try {
      verifyUuid();
    } catch (Throwable e) {
      e.printStackTrace();
      // todo uuid 가 변경됨, 다시 인증 필요
      intent = null;
      showUuidDialog();
    } finally {
      if (null != intent) {
        startActivity(intent);
      }
    }
  }

  @Override
  public void startActivity(Intent intent) {
    super.startActivity(intent);
    overridePendingTransition(R.anim.none, R.anim.none);
  }

  private void showUuidDialog() {
    DialogBuilder.create(DialogID.ALERT)
      .listener(new IDialogResultListener() {
        @Override
        public void onDialogResult(DialogBase dialog, Event event) {

        }

        @Override
        public void onDialogCanceled(DialogBase dialog) {
          Intent intent = new Intent(SplashActivity.this, SignUpActivity.class);
          startActivity(intent);
        }
      })
      .attribute((IAttribute<AlertDialog>) dialog -> {
        dialog.setText("UUID 가 변경되어 본인 인증이 필요합니다.");
      })
      .show();
  }

  protected void verifyUuid() {

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
      // fixme Manifest.permission.READ_PHONE_STATE 필요
      Log.e("APP#  SplashActivity | verifyUuid", "| " + "Manifest.permission.READ_PHONE_STATE 필요");
      return;
    }

    String uuid = SuperModel.getInstance().getPreferences().getDeviceUuid();
    String currentUuid = AppUtil.getDeviceUUID(this);

    if (StringUtil.isFull(uuid)) {
      // 현재 장치 값과 저장된 값이 같은지 검증;
      if (uuid.equals(currentUuid)) {
        // 이상 없음
        Log.w("APP# SplashActivity | verifyUuid", "|" + "이상 없음");
      }
      else {
        Log.e("APP#  SplashActivity | verifyUuid", "| " + "uuid 가 변경됨");
        throw new RuntimeException("uuid changed.");
      }
    }
    else {
      // 저장돼있지 않으면 처음이므로 저장;
      Log.w("APP# SplashActivity | verifyUuid", "|" + "저장돼있지 않으면 처음이므로 저장");
      setDeviceUuid(currentUuid);
    }
  }

  protected void setDeviceUuid(String uuid) {
    Log.w("APP# SplashActivity | setDeviceUuid", "| " + uuid);
    SuperModel.getInstance().setDeviceUuid(uuid);
  }

  protected void requestPermissions() {
    PermissionUtil.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, 99);
  }

  @Override
  public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestCode) {
      case 1001: {
        // If request is cancelled, the result arrays are empty.
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
          // permission was granted, yay! Do the
        }
        else {
          // permission denied, boo! Disable the
        }
        break;
      }
      default:
        break;
    }
  }
}

