package cn.m4399.operate.samples;

import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import cn.m4399.operate.OperateCenter;
import cn.m4399.operate.OperateCenterConfig;
import cn.m4399.operate.User;

import static cn.m4399.operate.OperateCenterConfig.PopLogoStyle;
import static cn.m4399.operate.OperateCenterConfig.PopWinPosition;

public class MainActivity extends FragmentActivity {
    public static final String TAG = "【DEMO】";

    private static final String GAME_KEY = "40027";
    private static final int GAME_ORIENTATION = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
    private static final boolean GAME_SUPPORT_EXCESS = true;

    private OperateCenter mOpeCenter;

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

        setRequestedOrientation(GAME_ORIENTATION);

        initSDK();
        setContentView(R.layout.main_activity);
        showSDKVersion();
    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        setContentView(R.layout.main_activity);
        showSDKVersion();
    }

    private void showSDKVersion() {
        TextView textView = findViewById(R.id.text_version);
        textView.setText(getString(R.string.demo_and_sdk_info, OperateCenter.getVersion(), GAME_KEY));
    }

    private void initSDK() {
        mOpeCenter = OperateCenter.getInstance();

        // 配置全局属性，如横竖屏配置，完整的详细说明见接入文档
        OperateCenterConfig config = new OperateCenterConfig.Builder(this)
                // 设置调试模式，可选，true时打开，默认false,发布前必须设置为false或删除该行
                .setDebugEnabled(false)
                // 设置游戏运营 key，此参数需要在原创开放平台注册应用后得到
                .setGameKey(GAME_KEY)
                // 设置SDK页面方向，应与游戏方向一致，部分第三方页面需要在AndroidManifest中设置
                .setOrientation(GAME_ORIENTATION)
                // 设置悬浮窗风格，有四种
                .setPopLogoStyle(PopLogoStyle.POPLOGOSTYLE_FOUR)
                // 设置悬浮窗初始位置，有四种，分别在屏幕上下左右
                .setPopWinPosition(PopWinPosition.POS_LEFT)
                // 设置游戏充值是否支持超出金额，true时支持，默认true
                // 也可以每次充值通过 OperateCenter.setSupportExcess 设置
                .setSupportExcess(GAME_SUPPORT_EXCESS)
                .build();
        mOpeCenter.setConfig(config);

        // A1: 初始化SDK
        // 此过程中检查当前帐号是否在登录中，只有在init之后， isLogin()返回的状态才可靠
        // 注意：初始化完成后，其他接口才可用
        mOpeCenter.init(MainActivity.this, new OperateCenter.OnInitGloabListener() {
            // 执行化结果处理
            @Override
            public void onInitFinished(boolean isLogin, User userInfo) {
                String state = isLogin ? getString(R.string.login_already) : getString(R.string.login_not_yet);
                toastAndLog(getString(R.string.init_result, state, userInfo.toString()));
            }

            /*
             * 注销帐号的回调
             * @param fromUserCenter fromUserCenter区分是否是从悬浮窗-个人中心("4399游戏助手页面")注销的，若是则为true，不是为false
             */
            @Override
            public void onUserAccountLogout(boolean fromUserCenter) {
                toastAndLog(getString(fromUserCenter ? R.string.logout_from_user_center : R.string.logout_not_from_user_center));
            }

            // 个人中心里切换帐号的回调
            @Override
            public void onSwitchUserAccountFinished(boolean fromUserCenter, User userInfo) {
                String result = fromUserCenter ?
                        getString(R.string.switch_account_from_user_center, userInfo) :
                        getString(R.string.switch_account_not_from_user_center, userInfo);
                toastAndLog(result);
            }
        });
    }

    private void destroySDK() {
        if (mOpeCenter != null)
            mOpeCenter = null;
    }

    public void onLoginBtnClicked(final View view) {
        view.setClickable(false);
        // B: 登录
        if (!mOpeCenter.isLogin()) // 注意：SDK 只是检查当前运行时状态，游戏应该去服务端检查或者每次都调用登录接口
            mOpeCenter.login(MainActivity.this, new OperateCenter.OnLoginFinishedListener() {
                @Override
                public void onLoginFinished(boolean success, int resultCode, User userInfo) {
                    String r = success ? getString(R.string.demo_success) : getString(R.string.demo_failed);
                    toastAndLog(getString(R.string.login_result, r, resultCode, userInfo));
                    view.setClickable(true);
                }
            });
        else {
            toastAndLog(getString(R.string.login_already));
            view.setClickable(true);
        }
    }

    public void onRechargeBtnClicked(View view) {
        // 在某次充值调用前设置，以满足不同充值场景需求
        // mOpeCenter.setSupportExcess(GAME_SUPPORT_EXCESS);

        // 模拟生成游戏唯一订单号，支持字母数字和字符‘-’，‘_’，‘|’
        String mark = "year|mon-hour_" + System.currentTimeMillis();
        if (mark.length() > 32)
            mark = mark.substring(0, 32);

        // C：充值
        // 金额是正整数，单位元
        // 商品名可选，但在充值页面显示规则不同，具体见接入文档
        mOpeCenter.recharge(this, 1, mark,
                getString(R.string.recharge_product_name),
                new OperateCenter.OnRechargeFinishedListener() {
                    @Override
                    public void onRechargeFinished(boolean success, int resultCode, String msg) {
                        toastAndLog(resultCode + ": " + msg);
                    }
                });
    }

    public void onSwitchAccountBtnClicked(final View view) {
        view.setClickable(false);
        // A2：切换账号
        mOpeCenter.switchAccount(this, new OperateCenter.OnLoginFinishedListener() {
            @Override
            public void onLoginFinished(boolean success, int resultCode, User userInfo) {
                String r = success ? getString(R.string.demo_success) : getString(R.string.demo_failed);
                toastAndLog(getString(R.string.login_result, r, resultCode, userInfo));
                view.setClickable(true);
            }
        });
    }

    public void onLogoutBtnClicked(View view) {
        // D：登出
        mOpeCenter.logout();
    }

    public void onCheckLoginBtnClicked(View view) {
        // 查询账号是否在登录中
        toastAndLog(getString(mOpeCenter.isLogin() ? R.string.login_already : R.string.login_not_yet));
    }

    public void onShowUserBtnClicked(View view) {
        // 查询当前用户信息
        toastAndLog(String.valueOf(mOpeCenter.getCurrentAccount()));
    }

    public void onServerBtnClicked(View view) {
        // 设置区服id，应在用户选取区服后设置
        mOpeCenter.setServer(String.valueOf(new Random().nextInt(100)));
    }

    public void onCheckBindPhoneBtnClicked(View view) {
        // 查询手机绑定状态
        mOpeCenter.checkBindPhoneState(new OperateCenter.OnCheckPhoneBindStateListener() {
            @Override
            public void onCheckPhoneBindState(int resultCode, String msg) {
                toastAndLog(msg);
            }
        });
    }

    public void onBindPhoneBtnClicked(View view) {
        // 绑定手机
        mOpeCenter.bindPhone(this, new OperateCenter.OnPhoneBindResultListener() {
            @Override
            public void onPhoneBindResult(int resultCode, String msg) {
                toastAndLog(getString(R.string.check_bind_phone_result, resultCode, msg));
            }
        });
    }

    public void onUpgradeBtnClicked(View view) {
        // 自定义更新
        new UpgradeController().doUpgrade(MainActivity.this, view);
    }

    public void onQuitGameBtnClicked(View view) {
        // 游戏退出
        mOpeCenter.shouldQuitGame(MainActivity.this, new OperateCenter.OnQuitGameListener() {
            @Override
            public void onQuitGame(boolean shouldQuit) {
                toastAndLog("Agree quit game? " + shouldQuit);
                if (shouldQuit) {
                    destroySDK();
                    finish();
                    // android.os.Process.killProcess(android.os.Process.myPid());
                }
            }
        });
    }

    public void onGoCommentClicked(View view) {
        // 前往游戏评论页
        mOpeCenter.showGameCommentArea(this);
    }

    public void onReportViolationBtnClicked(View view) {
        // 违规举报
        Random random = new Random();// 随机数生成
        int r = random.nextInt(100);
        Map<String, String> violation = new HashMap<>();
        violation.put("g_uid", "被举报人uid" + r);
        violation.put("g_tid", "聊天频道ID" + r);
        violation.put("g_sid", "服务器ID" + r);
        violation.put("g_rid", "角色ID" + r);
        violation.put("g_content", "聊天内容" + r);
        violation.put("g_role", "角色名称" + r);
        violation.put("g_gname", "公会名" + r);
        violation.put("g_cname", "宠物名" + r);
        mOpeCenter.reportViolation(MainActivity.this, violation);
    }

    @Override
    public void onBackPressed() {
        onQuitGameBtnClicked(null);
    }

    private void toastAndLog(String msg) {
        Toast.makeText(MainActivity.this, TAG + msg, Toast.LENGTH_SHORT).show();
        Log.d(TAG, msg);
    }
}
