package com.longtu.sample;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.Display;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import com.bh.sdk.Interface.LTBaseSDK;
import com.bh.sdk.LTGameUserData;
import com.longtu.sdk.base.LTBaseParam;
import com.longtu.sdk.base.Listener.LTBaseCallbackCode;
import com.longtu.sdk.base.Listener.LTBaseSDKListener;
import com.longtu.sdk.base.Listener.LTBaseSDKNoticeListener;
import com.longtu.sdk.base.Listener.LTBaseUserAgreementListener;
import com.longtu.sdk.utils.Log.Logs;

import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

/**
 * Demo 主Activity。 用户调用SDK的初始化和各个生命周期。
 */
public class LTBase_Demo_MainActivity extends Activity implements OnClickListener {

    public final static String LOGTAG = "ltbase_demo";

    // 是否需要初始化完成以后 自动登录
    public static boolean AutoLogin = false;

    // 是否初始化成功
    public static boolean isInitSuccess = false;

    public static boolean canswitchaccount;
    public static boolean canlogout;
    public static boolean cangocenter;

    private final static String gameResVer = "1";
    public static String RoleLv = "100";
    public static String RoleVipLv = "6";
    public final static String ServerName = "DEMO测试";
    public static String ServerId = "1";
    public static String LONGTU_RoleId = "1";

    public static String LONGTU_UserName;
    public static String LONGTU_UserId;

    public static LTBase_Demo_MainActivity mMainActivity;
    private LTBase_Demo_MainView mMainView;
    private LTBase_Demo_CreatUserView mCreatUserView;
    public static LTBase_Demo_PayView mPayView = null;


    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mMainActivity = this;
        // 设置无标题(DEMO代码)
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        // // 设置全屏幕(DEMO代码)
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        int currentApiVersion = Build.VERSION.SDK_INT;
        if (currentApiVersion >= 14) {
            WindowManager.LayoutParams params = getWindow().getAttributes();
            params.systemUiVisibility = View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
            getWindow().setAttributes(params);
        }

        // 强制使屏幕一直处于活动状态，不关闭背景光(DEMO代码)
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        // 设置打开日志输出，出正式包时务必注释掉(SDK接口)
        LTBaseSDK.getInstance(this).setLogs(true);

        Uri data = getIntent().getData();
        Logs.i(LOGTAG, " onCreate  data = " + data);
        if (data != null) {
            String scheme = data.getScheme();
            String Host = data.getHost();
            Logs.i(LOGTAG, " onCreate  scheme = " + scheme + "  Host = " + Host);

            List<String> params = data.getPathSegments();
            String PathSegments = "";
            for (int i = 0; i < params.size(); i++) {
                PathSegments = PathSegments + params.get(i);
            }
            Logs.i(LOGTAG, " onCreate  PathSegments = " + PathSegments);

            Toast.makeText(this, "scheme = " + scheme + "  Host = " + Host + " " + PathSegments, Toast.LENGTH_LONG);
        }

        // 初始化SDK
        LTBaseSDK.getInstance(this).LTBaseSDKInit(gameResVer, new LTBaseSDKListener() {

            @Override
            public void LTBaseSDKExitgameCallBack(int arg0, String arg1) {
                // TODO Auto-generated method stub
                LTBase_Demo_MainActivity.this.finish();
            }

            @Override
            public void LTBaseSDKInitCallBack(int code, String arg1) {
                // TODO Auto-generated method stub
                if (LTBaseCallbackCode.CODE_INIT_SUCCESS == code) {
                    isInitSuccess = true;
                    // 游戏实现
                    Toast.makeText(LTBase_Demo_MainActivity.this, "初始化成功 , code ==" + code, Toast.LENGTH_LONG).show();

                    if (AutoLogin) {
                        LTBaseSDK.getInstance(LTBase_Demo_MainActivity.mMainActivity).LTBaseSDKShowLoginView();
                    }
                } else {
                    Toast.makeText(LTBase_Demo_MainActivity.this, "初始化失败, code == " + code, Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void LTBaseSDKLoginCallBack(int code, String msg, LTGameUserData arg2) {
                // TODO Auto-generated method stub
                if (code == LTBaseCallbackCode.CODE_LOGIN_SUCCESS) {

                    Logs.i(LOGTAG, "MainActivity, tokenId == " + msg + ", user data == " + arg2.toString());

                    LONGTU_UserId = arg2.getUid();
                    Toast.makeText(LTBase_Demo_MainActivity.this, "登陆成功 Return:" + arg2.getReturnJson(), Toast.LENGTH_LONG).show();
                    // 初始化角色选择界面，游戏不需要关注
                    initGameChooseRole();
                } else {
                    Toast.makeText(LTBase_Demo_MainActivity.this, "登陆失败了, code == " + code, Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void LTBaseSDKSwitchLoginCallBack(int code, String msg, LTGameUserData userData) {
                if (code == LTBaseCallbackCode.CODE_LOGIN_SUCCESS) {
                    Logs.i(LOGTAG, "MainActivity, tokenId == " + msg + ", user data == " + userData.toString());
                    Toast.makeText(LTBase_Demo_MainActivity.this, "切换账号登陆成功", Toast.LENGTH_LONG).show();
                    // 初始化角色选择界面，游戏不需要关注
                    initGameChooseRole();
                } else {
                    Toast.makeText(LTBase_Demo_MainActivity.this, "切换账号 登陆失败了, code == " + code, Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void LTBaseSDKLogoutCallBack(int arg0, String arg1) {
                // TODO Auto-generated method stub
                Toast.makeText(LTBase_Demo_MainActivity.this, "注销成功", Toast.LENGTH_SHORT).show();
                // 返回登录界面，DEMO逻辑，游戏无需关注
                initGameLogin();
            }

            @Override
            public void LTBaseSDKPayCallBack(int code, String pbid, String orderID) {
                // TODO Auto-generated method stub
                if (code == LTBaseCallbackCode.CODE_PAY_SUCCESS) {
                    Logs.i(LOGTAG, "CODE_PAY_SUCCESS code == " + code + " , pbid = " + pbid + " ,orderID = " + orderID);
                    Toast.makeText(LTBase_Demo_MainActivity.this, "花钱成功了。。。*_*", Toast.LENGTH_SHORT).show();
                } else if (code == LTBaseCallbackCode.CODE_PAY_FAIL) {
                    Logs.i(LOGTAG, "CODE_PAY_FAIL code == " + code + " , pbid = " + pbid + " ,orderID = " + orderID);
                    Toast.makeText(LTBase_Demo_MainActivity.this, "支付失败了", Toast.LENGTH_SHORT).show();
                } else if (code == LTBaseCallbackCode.CODE_PAY_CANCEL) {
                    Logs.i(LOGTAG, "CODE_PAY_CANCEL code == " + code + " , pbid = " + pbid + " ,orderID = " + orderID);
                    Toast.makeText(LTBase_Demo_MainActivity.this, "支付取消了", Toast.LENGTH_SHORT).show();
                } else if (code == LTBaseCallbackCode.CODE_PAY_UNKNOWN) {
                    Logs.i(LOGTAG, "CODE_PAY_UNKNOWN code == " + code + " , pbid = " + pbid + " ,orderID = " + orderID);
                    Toast.makeText(LTBase_Demo_MainActivity.this, "下单成功", Toast.LENGTH_SHORT).show();
                }
            }

//            @Override
//            public void LTBaseSDKPayCallBack(int code, String pbid, String orderID, LTChargeInfo chargeInfo) {
//
//            }
        });

        LTBaseSDK.getInstance(this).LTBaseSetAgreementListener(mLTBaseUserAgreementListener);


        // 设置登录公告和游戏内活动公告事件回调
        LTBaseSDK.getInstance(this).LTBaseSetSDKNoticeListener(mLTBaseSDKNoticeListener);

        // 获取当前渠道SDK可选接口中哪些接口需要调用,必须放到SDK初始化后调用(SDK接口)
        canlogout = LTBaseSDK.getInstance(this).isLogoutEnable();
        canswitchaccount = LTBaseSDK.getInstance(this).isSwitchAccountEnable();
        cangocenter = LTBaseSDK.getInstance(this).isUserCenterEnable();

        // 游戏实现
        // 初始化游戏登陆界面
        initGameLogin();

    }

    /**
     * 隐私协议 信息
     */
    private LTBaseUserAgreementListener mLTBaseUserAgreementListener = new LTBaseUserAgreementListener() {

        @Override
        public void UserAgreementOpen() {
            Logs.i(LOGTAG, " UserAgreementOpen");
            Toast.makeText(LTBase_Demo_MainActivity.this, " 隐私协议打开 ", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void UserAgreementResult(boolean isAgree, JSONObject agreeDetails) {
            Logs.i(LOGTAG, " UserAgreementResult isAgree:" + isAgree + "  agreeDetails:" + agreeDetails);
            Toast.makeText(LTBase_Demo_MainActivity.this, " 隐私协议是否同意 isAgree:" + isAgree, Toast.LENGTH_SHORT).show();
        }
    };
    /**
     * 登录公告和游戏内活动公告打开关闭事件
     */
    private LTBaseSDKNoticeListener mLTBaseSDKNoticeListener = new LTBaseSDKNoticeListener() {

        /**
         * 登录公告打开事件，只有页面存在的时候，才会有打开的效果
         */
        @Override
        public void LTBaseSDKLoginNoticeStart() {
            Toast.makeText(LTBase_Demo_MainActivity.this, " 登录公告打开事件 ", Toast.LENGTH_SHORT).show();
        }

        /**
         * 登录公告关闭事件
         */
        @Override
        public void LTBaseSDKLoginNoticeClose() {
            Toast.makeText(LTBase_Demo_MainActivity.this, " 登录公告关闭事件 ", Toast.LENGTH_SHORT).show();
        }

        /**
         * 登录公告不存在，
         * 调用打开公告接口的时候，发现公告不存在的时候被调用
         */
        @Override
        public void LTBaseSDKNoLoginNotice() {
            Toast.makeText(LTBase_Demo_MainActivity.this, " 登录公告不存在 ", Toast.LENGTH_SHORT).show();
        }

        /**
         * 活动公告打开事件，只有页面存在的时候，才会有打开的效果
         */
        @Override
        public void LTBaseSDKActivityNoticeStart() {
            Toast.makeText(LTBase_Demo_MainActivity.this, " 活动公告打开事件 ", Toast.LENGTH_SHORT).show();
        }

        /**
         * 活动公告关闭事件
         */
        @Override
        public void LTBaseSDKNoActivityNotice() {
            Toast.makeText(LTBase_Demo_MainActivity.this, " 活动公告不存在 ", Toast.LENGTH_SHORT).show();
        }

        /**
         * 活动公告关闭事件，
         * 活动公告被关闭的时候展示
         */
        @Override
        public void LTBaseSDKActivityNoticeClose(String data) {
            Toast.makeText(LTBase_Demo_MainActivity.this, " 活动公告关闭事件 data = " + data, Toast.LENGTH_SHORT).show();
        }
    };

    /**
     * 初始化登陆界面
     */
    public void initGameLogin() {
        System.gc();
        mMainView = new LTBase_Demo_MainView(this);
        setContentView(mMainView);
        LTBaseSDK.getInstance(this).LTBaseSendGameProcess(LTBaseParam.GAME_PROCESS_EVENT_TYPE_IN_SELECT_SERVERLIST);
        if (mPayView != null) {
            mPayView.removeAllViews();
            mPayView = null;
        }
        if (mCreatUserView != null) {
            mCreatUserView.removeAllViews();
            mCreatUserView = null;
        }

        /*Intent intent=new Intent(this, LTBase_Demo_Ads.class);
        startActivity(intent);*/

    }

    /**
     * 初始化选择角色界面
     */
    private void initGameChooseRole() {
        System.gc();
        mCreatUserView = new LTBase_Demo_CreatUserView(this, new LTBase_Demo_CreatUserView.InGameCallback() {

            @Override
            public void InGame() {
                // TODO Auto-generated method stub
                initInGame();
            }
        });
        setContentView(mCreatUserView);

        if (mPayView != null) {
            mPayView.removeAllViews();
            mPayView = null;

            // 从主页面回来的，直接回到了 切换角色页面，所以这里也做一个选择角色服务器的事件
            LTBaseSDK.getInstance(this).LTBaseSendGameProcess(LTBaseParam.GAME_PROCESS_EVENT_TYPE_IN_SELECT_SERVERLIST);
        }
        if (mMainView != null) {
            mMainView.removeAllViews();
            mMainView = null;
        }

    }

    /**
     * 初始化游戏中
     */
    private void initInGame() {
        System.gc();
        mPayView = new LTBase_Demo_PayView(this);
        setContentView(mPayView);
        LTBaseSDK.getInstance(this).LTBaseSendGameProcess(LTBaseParam.GAME_PROCESS_EVENT_TYPE_OUT_SELECT_SERVERLIST);
        if (mMainView != null) {
            mMainView.removeAllViews();
            mMainView = null;
        }
        if (mCreatUserView != null) {
            mCreatUserView.removeAllViews();
            mCreatUserView = null;
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        Logs.i(LOGTAG, "onKeyDown  keyCode = " + keyCode + " event getRepeatCount = " + event.getRepeatCount());
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            // (SDK接口)
            if (mPayView != null && mPayView.mAnalyticslayout != null) {
                mPayView.mAnalyticslayout.onKeyDown(keyCode, event);
            } else if (mPayView != null && mPayView.mShareView != null) {
                mPayView.mShareView.onKeyDown(keyCode, event);
            } else {
                LTBaseSDK.getInstance(this).LTBaseSDKExitGame();
            }

            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClick(View view) {
        // TODO Auto-generated method stub

    }

    /**
     * 保存数据到应用手机内存，DEMO使用的方法
     *
     * @param context
     * @param b
     * @param filename
     */
    public static boolean SaveDataToPhone(Context context, byte[] b, String filename) {
        try {
            FileOutputStream fos = context.openFileOutput(filename, Context.MODE_APPEND);
            DataOutputStream dos = new DataOutputStream(fos);
            try {
                dos.write(b);
                dos.close();
                fos.close();
                return true;
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                Logs.i(LOGTAG, "SaveDataToPhone is err , e == " + e);
            }
            dos = null;
            fos = null;
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Logs.i(LOGTAG, "SaveDataToPhone is err , e == " + e);
        }
        return false;
    }

    /**
     * 从应用手机内存中获取数据，DEMO使用的方法
     *
     * @param context
     * @param filename
     * @return
     */
    public static byte[] GetDataFromPhone(Context context, String filename) {
        byte[] b = null;
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            FileInputStream fis = context.openFileInput(filename);
            DataInputStream dis = new DataInputStream(fis);
            try {
                int a = -1;
                while ((a = dis.read()) != -1) {
                    bos.write(a);
                }
                if (bos.size() > 0) {
                    b = bos.toByteArray();
                }
                bos.close();
                dis.close();
                fis.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                Logs.i(LOGTAG, "GetDataFromPhone is err , e == " + e);
            }
            bos = null;
            dis = null;
            fis = null;
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            Logs.i(LOGTAG, "GetDataFromPhone is err , e == " + e);
        }
        return b;
    }

    // ////////////////////////////////////一下为Activity生命周期的调用//////////////////////

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        Logs.i(LOGTAG, "onPause");
        // 必须调用
        LTBaseSDK.getInstance(this).onPause();
    }

    @Override
    protected void onRestart() {
        // TODO Auto-generated method stub
        super.onRestart();
        Logs.i(LOGTAG, "onRestart");
        // 必须调用
        LTBaseSDK.getInstance(this).onRestart();
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        Logs.i(LOGTAG, "onResume");
        // 必须调用
        LTBaseSDK.getInstance(this).onResume();


        if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
        }
    }

    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        Logs.i(LOGTAG, "onStart");
        // 必须调用
        LTBaseSDK.getInstance(this).onStart();
    }

    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
        Logs.i(LOGTAG, "onStop");
        // 必须调用
        LTBaseSDK.getInstance(this).onStop();
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        Logs.i(LOGTAG, "onDestroy");
        // 必须调用
        LTBaseSDK.getInstance(this).onDestroy();
        // 杀掉进程（游戏可以在onDestroy方法中杀掉进程）
        android.os.Process.killProcess(android.os.Process.myPid());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        Logs.i(LOGTAG, "onActivityResult");

        // 图片选择完成
        if (requestCode == 12345 && resultCode == RESULT_OK) {
            Uri uri = data.getData();
            Logs.i(LOGTAG, " uri =  " + LTBase_Demo_ImagePath.getPath(LTBase_Demo_MainActivity.this, uri));
            PhotoShare(LTBase_Demo_ImagePath.getPath(LTBase_Demo_MainActivity.this, uri));
        } else if (requestCode == LTBase_Demo_ShareView.Image_requestCode && resultCode == RESULT_OK) {
            if (mPayView != null && mPayView.mShareView != null) {
                Uri uri = data.getData();
                mPayView.mShareView.share_image(LTBase_Demo_ImagePath.getPath(LTBase_Demo_MainActivity.this, uri));
            }

        } else {
            Logs.i(LOGTAG, "onActivityResult");
            // 必须调用
            LTBaseSDK.getInstance(this).onActivityResult(requestCode, resultCode, data);
        }
    }

    private void PhotoShare(String imagepath) {


    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        // TODO Auto-generated method stub
        super.onConfigurationChanged(newConfig);
        Logs.i(LOGTAG, "onConfigurationChanged");
        // 必须调用
        LTBaseSDK.getInstance(this).onConfigurationChanged(newConfig);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        // TODO Auto-generated method stub
        super.onNewIntent(intent);
        Logs.i(LOGTAG, "onNewIntent");
        // 必须调用
        LTBaseSDK.getInstance(this).onNewIntent(intent);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        LTBaseSDK.getInstance(this).onBackPressed();
    }

    @Override
    protected void attachBaseContext(Context newBase) {
        // TODO Auto-generated method stub
        super.attachBaseContext(newBase);
        LTBaseSDK.getInstance(this).attachBaseContext(newBase);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        LTBaseSDK.getInstance(this).onRequestPermissionsResult(requestCode, permissions, grantResults);
    }


    /**
     * 获取屏幕的刷新频率
     */
    private void getRefreshRate() {
        Display display = LTBase_Demo_MainActivity.mMainActivity.getWindowManager().getDefaultDisplay();
        float refreshRate = display.getRefreshRate();
        Logs.i("demo", " refreshRate:" + refreshRate);
    }


}


