package com.maplehaze.adsdk.demo;

import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.provider.Settings;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;

import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.maplehaze.adsdk.MaplehazeSDK;
import com.maplehaze.adsdk.bean.AdEffect;
import com.maplehaze.adsdk.bid.MhBiddingLossReason;
import com.maplehaze.adsdk.demo.utils.DensityUtil;
import com.maplehaze.adsdk.demo.utils.MhStatusBarUtil;
import com.maplehaze.adsdk.demo.utils.OaidGetHelper;
import com.maplehaze.adsdk.demo.utils.RestartUtl;
import com.maplehaze.adsdk.demo.utils.SharePfUtil;
import com.maplehaze.adsdk.demo.utils.ToastUtil;
import com.maplehaze.adsdk.splash.SplashAd;

import java.util.ArrayList;
import java.util.List;

public class SplashActivity extends FragmentActivity implements View.OnClickListener {

    private static final String TAG = "SplashActivity";

    private final static int SPLASH_DISPLAY_LENGTH = 3000;

    private static final String EXTRA_LOAD_AD_ONLY = "extra_load_ad_only";
    private static final String EXTRA_SERVER_CONFIG = "extra_server_config";
    private static final String EXTRA_POS_ID = "extra_pos_id";

    public static void skipSplashActivity(Context context, boolean loadSplashOnly, boolean isEnableServerConfig, String posId) {
        Intent intent = new Intent(context, SplashActivity.class);
        intent.putExtra(EXTRA_LOAD_AD_ONLY, loadSplashOnly);
        intent.putExtra(EXTRA_SERVER_CONFIG, isEnableServerConfig);
        intent.putExtra(EXTRA_POS_ID, posId);
        intent.setFlags(FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);

    }


    private ViewGroup mViewContainer;


    private final Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    Intent intent = new Intent(SplashActivity.this, MainActivity.class);
                    startActivity(intent);
                    break;
            }
            return false;
        }
    });

    private TextView mLogoTextView;

    // load splash only
    private boolean mLoadSplashOnly = false;
    private boolean mLoadSplashOnlyShowAd = false;
    private boolean isEnableServerConfig = false;
    private LinearLayout loadAdOnlyView;
    private Button loadAdOnlyDisplayButton;
    private TextView loadAdOnlyStatusTextView;

    private String mPosId;

    private boolean isEcpm;
    private boolean isAdCallback;
    private int biddingPrice;
    private boolean isNoBiddingCompatibilityModel;

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

        Log.d(TAG, "onCreate");
        setContentView(R.layout.activity_splash);
        MhStatusBarUtil.setStatusBarTranslucent(this);
        Intent intent = getIntent();
        mLoadSplashOnly = intent.getBooleanExtra(EXTRA_LOAD_AD_ONLY, false);
        isEnableServerConfig = intent.getBooleanExtra(EXTRA_SERVER_CONFIG, false);
        isNoBiddingCompatibilityModel = SharePfUtil.getNoBiddingCompatibilityModeSwitch(this);
        mPosId = intent.getStringExtra(EXTRA_POS_ID);
        isEcpm = SharePfUtil.getEcpmConfig(this);
        biddingPrice = SharePfUtil.getBiddingPrice(this);
        isAdCallback = SharePfUtil.getAdCallBackToastConfig(this);
        if (TextUtils.isEmpty(mPosId)) {
            mPosId = Constants.SPLASH_POS_ID;
        }



        mViewContainer = findViewById(R.id.splash_container);

        mLogoTextView = findViewById(R.id.splash_logo_textview);

        loadAdOnlyView = findViewById(R.id.splash_load_ad_only);
        Button loadAdOnlyCloseButton = findViewById(R.id.splash_load_ad_close);
        loadAdOnlyCloseButton.setOnClickListener(this);
        loadAdOnlyDisplayButton = findViewById(R.id.splash_load_ad_display);
        loadAdOnlyDisplayButton.setOnClickListener(this);
        Button loadAdOnlyRefreshButton = findViewById(R.id.splash_load_ad_refresh);
        loadAdOnlyRefreshButton.setOnClickListener(this);
        loadAdOnlyStatusTextView = findViewById(R.id.splash_load_ad_status);

        if (mLoadSplashOnly) {
            mLogoTextView.setVisibility(View.INVISIBLE);
            loadAdOnlyView.setVisibility(View.VISIBLE);
            loadAdOnlyStatusTextView.setText("广告加载中...");
            loadAdOnlyDisplayButton.setEnabled(false);
        }
        if (savedInstanceState!=null){
            RestartUtl.startClearLastTask(this);
        }else{
            getSplashAd();
        }
    }


    private SplashAd mSplashAd;

    private void getSplashAd() {
        Log.d(TAG, "getSplashAd");
        if (!MaplehazeSDK.getInstance().isInitFinish()){
            Log.i(TAG,"sdk not init wait for init");
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    Log.i(TAG,"wait for init timeout");
                    getSplashAd();
                }
            },300);
        }else{
            Log.i(TAG,"sdk init finish");
            requestAd();//请求广告
        }
    }

    private void requestAd(){
        OaidGetHelper.getInstance().initOaid(getApplicationContext());
        SplashAd.SplashAdListener listener = new SplashAd.SplashAdListener() {

            /**
             * 广告加载
             */
            @SuppressLint("SetTextI18n")
            @Override
            public void onADLoaded(long expireTimestamp) {
                Log.i(TAG, "onADLoaded");
                ToastUtil.showToast(getApplicationContext(), R.string.mh_demo_load_ad_success);
                if (mLoadSplashOnly) {
                    loadAdOnlyDisplayButton.setEnabled(true);
                    long timeIntervalSec = (expireTimestamp - SystemClock.elapsedRealtime()) / 1000;
                    long min = timeIntervalSec / 60;
                    long second = timeIntervalSec - (min * 60);
                    loadAdOnlyStatusTextView.setText("加载成功,广告将在:" + min + "分" + second + "秒后过期，请在此之前展示(showAd)");
                } else {
                    biddingAndShowAd();
                }
            }

            /**
             * 广告展示
             */
            @Override
            public void onADPresent() {
                Log.i(TAG, "onADPresent");
                if (isAdCallback) {
                    ToastUtil.showToast(getApplicationContext(), R.string.mh_demo_ad_show);
                }
            }

            /**
             * 广告点击
             */
            @Override
            public void onADClicked() {
                if (isAdCallback) {
                    ToastUtil.showToast(getApplicationContext(), R.string.mh_demo_ad_click);
                }
                Log.i(TAG, "onSplashADClicked");
            }

            /**
             * 广告跳转
             */
            @Override
            public void onADDismissed() {
                if (isAdCallback) {
                    ToastUtil.showToast(getApplicationContext(), R.string.mh_demo_ad_jump);
                }
                Log.i(TAG, "onADDismissed");
                finish();
            }

            /**
             * 无广告
             */
            @Override
            public void onNoAD() {
                Log.i(TAG, "onNoAD");
                ToastUtil.showToast(getApplicationContext(), R.string.mh_demo_no_ad_result);
            }

            /**
             * 异常
             */
            @Override
            public void onADError(int error) {
                Log.i(TAG, "error==" + error);
                if (mLoadSplashOnly && !mLoadSplashOnlyShowAd) {
                    loadAdOnlyStatusTextView.setText(String.valueOf(error));
                    return;
                }
                ToastUtil.showToast(getApplicationContext(), getString(R.string.mh_demo_ad_error, error));
                jump();
            }


            /**
             * 倒计时
             */
            @Override
            public void onADTick(long l) {
                Log.d(TAG, "onADTick l=" + l);

            }
        };
        //传入Activity,支持的广告更多，部分广告只支持Activity
        mSplashAd = new SplashAd(this, mPosId, listener);
        mSplashAd.setViewSize(DensityUtil.getScreenRealWidth(this),
                DensityUtil.getScreenRealHeight(this)-DensityUtil.dpToPx(this,100));

//        mSplashAd = new SplashAd(this.getApplication(), mPosId, listener);
        //---------------only for test -----------------------
        if (SharePfUtil.getDevelopMode(this)){
            mSplashAd.setTestEnableServerConfig(true);// only for demo
        }else{
            mSplashAd.setTestEnableServerConfig(isEnableServerConfig);// only for demo
        }
        //---------------only for test -----------------------

        mSplashAd.loadAdOnly();//请求广告
    }



    //防止用户返回键退出APP
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME) {
            if (mLoadSplashOnly) {
                return super.onKeyDown(keyCode, event);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }



    /**
     * 不可点击的开屏，使用该jump方法，而不是用jumpWhenCanClick
     */
    private void jump() {
        Log.i(TAG, "jump");
        mHandler.sendEmptyMessageDelayed(1, SPLASH_DISPLAY_LENGTH);
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "onResume");

    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "onPause");

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mSplashAd != null) {
            mSplashAd.destroy();
            mSplashAd = null;
        }
        mHandler.removeCallbacks(null);
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.splash_load_ad_close:
                this.finish();
                break;
            case R.id.splash_load_ad_refresh:
                if (mSplashAd != null) {
                    mLoadSplashOnlyShowAd = false;
                    mSplashAd.loadAdOnly();
                    this.loadAdOnlyStatusTextView.setText("广告加载中...");
                    loadAdOnlyDisplayButton.setEnabled(false);
                }
                break;
            case R.id.splash_load_ad_display:
                mLoadSplashOnlyShowAd = true;

                loadAdOnlyView.setVisibility(View.GONE);
                mLogoTextView.setVisibility(View.VISIBLE);
                biddingAndShowAd();
                break;
            default:
        }
    }

    private void biddingAndShowAd() {
        if (mSplashAd != null && mSplashAd.isValid()) {
            if (isNoBiddingCompatibilityModel) {//兼容非竞价模式广告位
                int adEcpm = mSplashAd.getEcpm();
                if (adEcpm == -1) {//非竞价广告
                    Log.d(TAG, "非竞价广告 adEcpm=" + adEcpm);
                    mSplashAd.showAd(mViewContainer);
                    if (isEcpm) {
                        ToastUtil.showToast(getApplicationContext(), getString(R.string.mh_demo_no_bidding_ecpm, adEcpm));
                    }
                } else if (biddingAd()) {//竞价模式
                    mSplashAd.showAd(mViewContainer);
                } else {
                    ToastUtil.showToast(getApplicationContext(), R.string.mh_demo_no_ad_result);
                    jump();
                }
            } else {//竞价模式
                if (biddingAd()) {
                    mSplashAd.showAd(mViewContainer);
                } else {
                    if (!isEcpm) {
                        ToastUtil.showToast(getApplicationContext(), R.string.mh_demo_no_bidding_ad);
                    }
                    jump();
                }
            }
        } else {
            ToastUtil.showToast(getApplicationContext(), R.string.mh_demo_no_ad_result);
            jump();
        }
    }

    private boolean biddingAd() {
        int adEcpm = mSplashAd.getEcpm();
        //竞价广告位需要和运营申请开通，非竞价模式返回的ecpm不作为有效价格
        int bidPrice = biddingPrice; //演示媒侧多预算价格过滤
        Log.d(TAG, "adEcpm=" + adEcpm + " bidPrice=" + bidPrice);
        boolean isWinBidding = false;
        if (adEcpm >= bidPrice) {
            //上报竞价成功，需要展示前上报
            int winPrice = adEcpm;//竞胜成交价
            mSplashAd.sendWinNotification(winPrice);
            isWinBidding = true;
            if (isEcpm) {
                ToastUtil.showToast(getApplicationContext(), getString(R.string.mh_demo_bidding_success, adEcpm));
            }
        } else {
            //MhBiddingLossReason.LOW_PRICE 竞争力不足
            //MhBiddingLossReason.NOT_COMPETITION 有广告回包但是未参与竞价
            //MhBiddingLossReason.NO_AD 无广告回包
            //MhBiddingLossReason.OTHER 其他（有回包）
            int winPrice = 1000;//竞胜方出价，接入的时候需要传入竞胜方出价
            mSplashAd.sendLossNotification(winPrice, MhBiddingLossReason.LOW_PRICE);
            if (isEcpm) {
                ToastUtil.showToast(getApplicationContext(), getString(R.string.mh_demo_bidding_fial, adEcpm));
            }
        }
        return isWinBidding;
    }


}
