package com.gensee.fastsdkdemo;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.gensee.common.GenseeConfig;
import com.gensee.common.ServiceType;
import com.gensee.entity.InitParam;
import com.gensee.fastsdk.GenseeLive;
import com.gensee.fastsdk.core.GSFastConfig;
import com.gensee.fastsdk.entity.GSMoreItem;
import com.gensee.fastsdk.entity.Marquee;
import com.gensee.fastsdk.util.GenseeUtils;
import com.gensee.fastsdkdemo.DemoConfig.LIVEMODE;
import com.gensee.glivesdk.GSLiveSDK;
import com.gensee.glivesdk.config.GSLiveConfig;
import com.gensee.glivesdk.config.LiveMode;
import com.gensee.glivesdk.config.PublishVideoConfig;
import com.gensee.glivesdk.config.PublishVideoQuality;
import com.gensee.glivesdk.config.PublishVideoRatio;
import com.gensee.utils.GenseeLog;
import com.gensee.utils.upload.FileUploader;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;


/**
 * MainActivity 测试启动，实际是构造InitParam和GSFastConfig
 * 分别如下
 * isPublishMode
 * 是否是发布端，true=发布端，false=观看端
 * domain 设置域名
 * <p>
 * 若一个url为http://test.gensee.com/site/training   域名是“test.gensee.com”</p>
 * number 直播或点播编号<p>设置对应编号，如果是点播则是点播编号，是直播便是直播编号。
 * 请注意不要将id理解为编号。
 * 作用等价于id，但不是id。有id可以不用编号，有编号可以不用id</p>
 * loginAccount 站点登录账号
 * <p> 设置站点认证账号 即登录站点的账号
 * loginPwd 站点登录密码
 * <p> 设置站点认证密码 即登录站点的密码
 * 可选，如果后台设置直播需要登录或点播需要登录，那么登录密码要正确  且帐号同时也必须填写正确 </p>
 * nickName 昵称
 * <p>设置昵称  用于直播间显示或统计   一定要填写</p>
 * joinPwd 直播口令
 * <p>设置口令 即直播的保护密码
 * 可选 如果后台设置了保护密码 请填写对应的口令</p>
 * k
 * 第三方认证K值
 * serviceType
 * 设置服务类型   webcast站点对应 WEBCAST   training 对应 TRAINING
 */

public class MainActivity extends Activity {
    private static final int PERMISSION_RESULT_CODE = 10000;
    private Spinner spServiceType, spMode, spPubSreenMode, spPubHardEncode, spPubQuality, spPubRatio;
    private Spinner spWatchScreenMode, spLocale;
    private View fixedMoneyLy, btnMoreSetting, btnDownload, pubParamSetLy, watchParamSetLy;
    private EditText mEditDomain, mEditNumber, mEidtAccount, mEidtAccountPwd, mEditNickName, mEditJoinPwd, mEditK, mEditUserId;
    private EditText etMoney1, etMoney2, etMoney3, etMoney4, etMoney5, etMoney6;
    private TextView tvVersion;
    private Button mBtnJoin;
    public static final String PARAMS_DOMAIN = "PARAMS_DOMAIN";
    public static final String PARAMS_TYPE = "PARAMS_TYPE";
    public static final String PARAMS_NUMBER = "PARAMS_NUMBER";
    public static final String PARAMS_ACCOUNT = "PARAMS_ACCOUNT";
    public static final String PARAMS_PWD = "PARAMS_PWD";
    public static final String PARAMS_NICKNAME = "PARAMS_NICKNAME";
    public static final String PARAMS_JOINPWD = "PARAMS_JOINPWD";
    public static final String PARAMS_SERVICE_TYPE = "PARAMS_SERVICE_TYPE";
    public static final String PARAMS_LIVE_MODE = "PARAMS_LIVE_MODE";
    public static final String PARAMS_PUB_SCREEN_MODE = "PARAMS_PUB_SCREEN_MODE";
    public static final String PARAMS_WATCH_SCREEN_MODE = "PARAMS_WATCH_SCREEN_MODE";
    public static final String PARAMS_HARD_ENCODE = "PARAMS_HARD_ENCODE";
    public static final String PARAMS_QUALITY = "PARAMS_QUALITY";
    public static final String PARAMS_RATIO = "PARAMS_RATIO";
    public static final String PARAMS_USERID = "PARAMS_USERID";

    private LIVEMODE liveMode;
    private ServiceType serviceType;
    private int defPubScreenMode,defWatchScreenMode,defQuality,defRatio;
    private boolean defPubHardEncode;
    private String defDomain = "",defNumber = "",defNickName = "",defJoinPwd = "",defAcc = "",defAccPwd = "",defUserId = "";
    private SharedPreferences preferences;
    private GSFastConfig gsFastConfig;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        int strId1 = getResources().getIdentifier("activity_main", "layout", "com.gensee.fastsdkdemo");
        setContentView(strId1);
        setTitle("FastSDKdemo(" + GenseeConfig.getSDKVersion() + ")");
        preferences = getSharedPreferences(SettingActivity.SETTING_PREFERENCES_NAME, MODE_PRIVATE);
        initWidget();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            List<String> permissions = new ArrayList<>();
            if (checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.RECORD_AUDIO);
            }
            if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.CAMERA);
            }
            if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            }
            int size = permissions.size();
            if (size > 0) {
                String[] ps = new String[size];
                permissions.toArray(ps);
                requestPermissions(ps, PERMISSION_RESULT_CODE);
            }
        }
    }

    private void initWidget() {
        mBtnJoin = findViewById(R.id.gs_bnt_room_join);
        mBtnJoin.setOnClickListener(v -> joinBtnOnClick());
        //固定金额配置,支持0-6个
        fixedMoneyLy = findViewById(R.id.gs_ll_fixed_money);
        btnMoreSetting = findViewById(R.id.gs_bnt_more_setting);
        btnMoreSetting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DemoConfig.getIns().setLivemode(liveMode);
                DemoConfig.getIns().setWatchScreenMode(defWatchScreenMode);
                startActivity(new Intent(MainActivity.this, SettingActivity.class));
            }
        });
        btnDownload = findViewById(R.id.gs_bnt_vod_download);
        btnDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                InitParam initParam = getInitParam();
                Intent i = new Intent(MainActivity.this, VodDownloadActivity.class);
                i.putExtra(VodDownloadActivity.PARAM, initParam);
                startActivity(i);
            }
        });
        pubParamSetLy = findViewById(R.id.pub_param_set_ly);
        watchParamSetLy = findViewById(R.id.watch_param_set_ly);
        etMoney1 = (EditText) findViewById(R.id.et_money1);
        etMoney2 = (EditText) findViewById(R.id.et_money2);
        etMoney3 = (EditText) findViewById(R.id.et_money3);
        etMoney4 = (EditText) findViewById(R.id.et_money4);
        etMoney5 = (EditText) findViewById(R.id.et_money5);
        etMoney6 = (EditText) findViewById(R.id.et_money6);

//		tvVersion = ((TextView) findViewById(R.id.version_tv));
//		tvVersion.setText("SDK" + GenseeConfig.getSDKVersion());

        spMode = findViewById(R.id.spMode);
        configSpinner(spMode, Arrays.asList(getString(R.string.watch_mode), getString(R.string.publish_mode), getString(R.string.vod_mode)),
                position -> {
                    switch (position) {
                        case 0:
                            liveMode = LIVEMODE.WATCH;
                            fixedMoneyLy.setVisibility(View.VISIBLE);
                            pubParamSetLy.setVisibility(View.GONE);
                            watchParamSetLy.setVisibility(View.VISIBLE);
//                        if(spWatchScreenMode.getSelectedItemPosition() == 0){
//                        }
                            btnMoreSetting.setVisibility(View.VISIBLE);
                            btnDownload.setVisibility(View.GONE);
                            break;
                        case 1:
                            liveMode = LIVEMODE.PUBLISH;
                            fixedMoneyLy.setVisibility(View.GONE);
                            pubParamSetLy.setVisibility(View.VISIBLE);
                            watchParamSetLy.setVisibility(View.GONE);
                            btnMoreSetting.setVisibility(View.GONE);
                            btnDownload.setVisibility(View.GONE);
                            break;
                        case 2:
                            liveMode = LIVEMODE.VOD;
                            btnMoreSetting.setVisibility(View.VISIBLE);
                            watchParamSetLy.setVisibility(View.GONE);
                            fixedMoneyLy.setVisibility(View.GONE);
                            pubParamSetLy.setVisibility(View.GONE);
                            btnDownload.setVisibility(View.GONE);
                            break;
                    }
                });

        /*观看端模式选择*/
        spWatchScreenMode = findViewById(R.id.sp_watch_screen_mode);
        configSpinner(spWatchScreenMode,Arrays.asList("分屏观看(文档+视频)","竖屏观看"),
                position -> {
                    switch (position) {
                        case 0:
                            defWatchScreenMode = GSFastConfig.WATCH_SCREEN_MODE_VIDEO_DOC;
//                        btnMoreSetting.setVisibility(liveMode == LIVEMODE.WATCH ? View.VISIBLE : View.GONE);
                            break;
                        case 1:
                            defWatchScreenMode = GSFastConfig.WATCH_SCREEN_MODE_PORTRAIT;
//                        btnMoreSetting.setVisibility(View.GONE );
                            break;
                    }
                });


        spServiceType = findViewById(R.id.spServiceType);
        configSpinner(spServiceType,Arrays.asList(getString(R.string.webcast_type),getString(R.string.training_type)),
                position -> {
                    switch (position) {
                        case 0:
                            serviceType = ServiceType.WEBCAST;
                            break;
                        case 1:
                            serviceType = ServiceType.TRAINING;
                            break;
                    }
                });
        /*发布端屏幕方向*/
        spPubSreenMode = findViewById(R.id.sp_pub_screen_mode);
        configSpinner(spPubSreenMode,Arrays.asList("视频文档","横屏直播","竖屏直播","G直播横屏","G直播竖屏"),
                position -> {
                    switch (position) {
                        case 0:
                            defPubScreenMode = GSFastConfig.PUB_SCREEN_MODE_VIDEO_AND_DOC;
                            break;
                        case 1:
                            defPubScreenMode = GSFastConfig.PUB_SCREEN_MODE_LANDSCAPE;
                            break;
                        case 2:
                            defPubScreenMode = GSFastConfig.PUB_SCREEN_MODE_PORTRAIT;
                            break;
                        case 3:
                            defPubScreenMode = GSFastConfig.PUB_SCREEN_MODE_G_LANDSCAPE;
                            break;
                        case 4:
                            defPubScreenMode = GSFastConfig.PUB_SCREEN_MODE_G_PORTRAIT;
                            break;
                    }
                    spPubRatio.setVisibility(position==0 ? View.VISIBLE : View.GONE);
                });
        /*发布端硬编/软编*/
        spPubHardEncode = findViewById(R.id.sp_pub_hard_encode);
        configSpinner(spPubHardEncode,Arrays.asList(getString(R.string.pub_hard_encode),getString(R.string.pub_soft_encode)),
                position -> defPubHardEncode = position == 0);
        /*发布端分辨率 超清,高清,普清*/
        spPubQuality = findViewById(R.id.sp_pub_quality);
        configSpinner(spPubQuality,Arrays.asList("超清","高清","标清"),
                position ->{
                    if (position == 0) {
                        defQuality = GSFastConfig.PUB_QUALITY_SHD;
                    } else if(position == 1){
                        defQuality = GSFastConfig.PUB_QUALITY_HD;
                    } else if (position == 2) {
                        defQuality = GSFastConfig.PUB_QUALITY_SD;
                    }
                });
        spPubRatio = findViewById(R.id.sp_pub_ratio);
        //只有发布端视频文档模式, 可以设置发布视频比例
//        spPubRatio.setVisibility(defPubScreenMode == GSFastConfig.PUB_SCREEN_MODE_VIDEO_AND_DOC ? View.VISIBLE : View.GONE);
        configSpinner(spPubRatio,Arrays.asList("4:3","16:9"),
                position -> defRatio = position == 0 ? GSFastConfig.PUB_RATIO_4_TO_3 : GSFastConfig.PUB_RATIO_16_TO_9);
        mEditDomain = (EditText) findViewById(R.id.gs_domin);
        mEditNumber = (EditText) findViewById(R.id.gs_numble);
        mEidtAccount = (EditText) findViewById(R.id.gs_account);
        mEidtAccountPwd = (EditText) findViewById(R.id.gs_account_psw);
        mEditNickName = (EditText) findViewById(R.id.gs_nickroom);
        mEditJoinPwd = (EditText) findViewById(R.id.gs_nickname_psw);
        mEditK = (EditText) findViewById(R.id.gs_k);
        mEditUserId = (EditText) findViewById(R.id.gs_userId);

//		defDomain = "192.168.1.108";
//		defNumber = "35816231";
//		defNickName = "fastsdk_test_android";
//		defJoinPwd = "333333";
//		defAcc = "admin@gensee.com";
//		defAccPwd = "888888";
//        GenseeConfig.isForceFlv = true;

        mEditDomain.setText(preferences.getString(PARAMS_DOMAIN, defDomain
        ));
        mEditNumber.setText(preferences.getString(PARAMS_NUMBER,
                defNumber));
        mEidtAccount.setText(preferences.getString(PARAMS_ACCOUNT, defAcc
        ));
        mEidtAccountPwd.setText(preferences.getString(PARAMS_PWD, defAccPwd
        ));
        mEditNickName.setText(preferences.getString(PARAMS_NICKNAME,
                defNickName));
        mEditJoinPwd.setText(preferences.getString(PARAMS_JOINPWD,
                defJoinPwd));
        mEditUserId.setText(preferences.getString(PARAMS_USERID,
                defUserId));
        String service = preferences.getString(PARAMS_SERVICE_TYPE,
                "training");
        if ("webcast".equals(service)) {
            spServiceType.setSelection(0);
        } else if ("training".equals(service)) {
            spServiceType.setSelection(1);
        }
        spPubSreenMode.setSelection(preferences.getInt(PARAMS_PUB_SCREEN_MODE, 0));
        spWatchScreenMode.setSelection(preferences.getInt(PARAMS_WATCH_SCREEN_MODE, 0));
        boolean isHardEncode = preferences.getBoolean(PARAMS_HARD_ENCODE, true);
        if (isHardEncode) {
            spPubHardEncode.setSelection(0);
        } else {
            spPubHardEncode.setSelection(1);
        }
        spPubQuality.setSelection(preferences.getInt(PARAMS_QUALITY, 0));
        spPubRatio.setSelection(preferences.getInt(PARAMS_RATIO, 0));

        liveMode = LIVEMODE.WATCH;
        spMode.setSelection(0);
        int mode = preferences.getInt(PARAMS_LIVE_MODE,
                LIVEMODE.WATCH.getValue());
        if (mode == LIVEMODE.PUBLISH.getValue()) {
            liveMode = LIVEMODE.PUBLISH;
            spMode.setSelection(1);
        } else if (mode == LIVEMODE.VOD.getValue()) {
            liveMode = LIVEMODE.VOD;
            spMode.setSelection(2);
        }
        initLocaleSpinner();
    }

    private void initLocaleSpinner() {
        spLocale = findViewById(R.id.sp_locale);
        configSpinner(spLocale,Arrays.asList("[切换语言]简体中文","[切换语言]繁体中文","[切换语言]英文"),
                position -> {
                    switch (position) {
                        case 0:
                            GenseeUtils.updateLocale(MainActivity.this, Locale.CHINA);
                            break;
                        case 1:
                            GenseeUtils.updateLocale(MainActivity.this, Locale.TRADITIONAL_CHINESE);
                            break;
                        case 2:
                            GenseeUtils.updateLocale(MainActivity.this, Locale.ENGLISH);
                            break;
                    }
                });
    }

    private InitParam getInitParam() {
        String domain = mEditDomain.getText().toString();
        String number = mEditNumber.getText().toString();
        String account = mEidtAccount.getText().toString();
        String pwd = mEidtAccountPwd.getText().toString();
        String nickName = mEditNickName.getText().toString();
        String joinPwd = mEditJoinPwd.getText().toString();
        String k = mEditK.getText().toString().trim();
        String userId = mEditUserId.getText().toString().trim();
        if ("".equals(domain) || "".equals(number)) {
            Toast.makeText(MainActivity.this, "域名和编号都不能为空", Toast.LENGTH_LONG)
                    .show();
            return null;
        }
        long luserId = 0;
        if (userId.length() >= 10) {
            luserId = Long.valueOf(userId);
        }

        preferences.edit().putString(PARAMS_DOMAIN, domain)
                .putString(PARAMS_NUMBER, number)
                .putString(PARAMS_ACCOUNT, account)
                .putString(PARAMS_PWD, pwd)
                .putString(PARAMS_NICKNAME, nickName)
                .putString(PARAMS_JOINPWD, joinPwd)
                .putString(PARAMS_USERID, luserId > 1000000000 ? userId : "")
                .putString(PARAMS_SERVICE_TYPE, serviceType.getValue())
                .putInt(PARAMS_LIVE_MODE, liveMode.getValue())
                .putInt(PARAMS_PUB_SCREEN_MODE, defPubScreenMode)
                .putInt(PARAMS_WATCH_SCREEN_MODE, defWatchScreenMode)
                .putBoolean(PARAMS_HARD_ENCODE, defPubHardEncode)
                .putInt(PARAMS_QUALITY, defQuality)
                .apply();

        InitParam initParam = new InitParam();
        //若一个url为http://test.gensee.com/site/webcast   域名是“test.gensee.com”
        initParam.setDomain(domain);
        //设置对应编号，如果是点播则是点播编号，是直播便是直播编号。
        //请注意不要将id理解为编号。
        //作用等价于id，但不是id。有id可以不用编号，有编号可以不用id
        initParam.setNumber(number);
        //设置站点认证账号 即登录站点的账号
        initParam.setLoginAccount(account);
        //设置站点认证密码 即登录站点的密码,如果后台设置直播需要登录或点播需要登录，那么登录密码要正确  且帐号同时也必须填写正确
        initParam.setLoginPwd(pwd);
        //设置昵称  用于直播间显示或统计   一定要填写
        initParam.setNickName(nickName);
        //可选 如果后台设置了保护密码 请填写对应的口令
        initParam.setJoinPwd(joinPwd);
        //第三方认证K值，如果启用第三方集成的时候必须传入有效的K值
        initParam.setK(k);
        //若一个url为http://test.gensee.com/site/webcast ,serviceType是 ServiceType.WEBCAST,
        //url为http://test.gensee.com/site/training,serviceTypeserviceType是 ServiceType.TRAINING
        initParam.setServiceType(serviceType);
        //自定义userid 大于10亿有效
        initParam.setUserId(luserId);
        return initParam;
    }

    protected void joinBtnOnClick() {
        InitParam initParam = getInitParam();
        if (initParam == null) {
            return;
        }
        gsFastConfig = new GSFastConfig();
        //点播和直播观看都有效的选项
        gsFastConfig.setHardDecode(getBooleanFromPrefrences(SettingActivity.GS_HARD_DECODE_VIDEO));//观看的视频硬件解码
        //分屏观看端、点播,界面配置
        gsFastConfig.setShowDoc(getBooleanFromPrefrences(SettingActivity.GS_DOC));
        gsFastConfig.setShowChat(getBooleanFromPrefrences(SettingActivity.GS_CHAT));
        gsFastConfig.setShowQa(getBooleanFromPrefrences(SettingActivity.GS_QA));
        gsFastConfig.setShowIntro(getBooleanFromPrefrences(SettingActivity.GS_INTRO));
        gsFastConfig.setBackGroudPlay(getBooleanFromPrefrences(SettingActivity.GS_BACKGROUD_PLAY));
        //跑马灯的配置
        Marquee marquee = new Marquee();
        marquee.content = getStringFromPrefrences(SettingActivity.GS_MARQUEE_CONTENT);//文字内容，最多100个字符,空则不显示 "您可以通过把发件人地址加入到地址本中避免该发件人的信件被投递到垃圾邮件文件夹。"
        marquee.textColor = preferences.getInt(SettingActivity.GS_MARQUEE_COLOR, Color.RED);//默认红色 如Color.RED;
        marquee.textSize = preferences.getInt(SettingActivity.GS_MARQUEE_SIZE, 14);//单位dp,默认14;
        marquee.speed = getSpeedFromPrefrences();//默认1速(Marquee.Speed.ONE)，2速在1速的基础*1.5，3速在1速的基础上*2，4速在1速的基础上*2.5，5速在1速的基础上*3
        gsFastConfig.setMarquee(marquee);
        addGSMoreItem(gsFastConfig);//添加自定义更多项
		//编号超过8位,认为是liveId,由于界面上只有一个输入编号的地方,这里直接转换了
        if (!TextUtils.isEmpty(initParam.getNumber()) && initParam.getNumber().length() > 8) {
            initParam.setLiveId(initParam.getNumber());
            initParam.setNumber("");
        }
        if (liveMode == LIVEMODE.VOD) {
            gsFastConfig.setShowChapter(getBooleanFromPrefrences(SettingActivity.GS_CHAPTER));
            //设置点播播放“暂无视频的背景图片”
//			gsFastConfig.setOnViewCallback(new GSFastConfig.OnViewCallback() {
//				@Override
//				public boolean onVodVideoDefaultView(View view) {
//					view.setBackground(getResources().getDrawable(R.drawable.fs_icon_no_doc));
//					return true;
//				}
//			});
            GenseeLive.startVod(this, initParam, gsFastConfig);
        } else {
            String money1 = etMoney1.getText().toString();
            String money2 = etMoney2.getText().toString();
            String money3 = etMoney3.getText().toString();
            String money4 = etMoney4.getText().toString();
            String money5 = etMoney5.getText().toString();
            String money6 = etMoney6.getText().toString();

            int[] arr = new int[6];
            arr[0] = Integer.valueOf(TextUtils.isEmpty(money1) ? "0" : money1);
            arr[1] = Integer.valueOf(TextUtils.isEmpty(money2) ? "0" : money2);
            arr[2] = Integer.valueOf(TextUtils.isEmpty(money3) ? "0" : money3);
            arr[3] = Integer.valueOf(TextUtils.isEmpty(money4) ? "0" : money4);
            arr[4] = Integer.valueOf(TextUtils.isEmpty(money5) ? "0" : money5);
            arr[5] = Integer.valueOf(TextUtils.isEmpty(money6) ? "0" : money6);
            boolean isPublishMode = liveMode == LIVEMODE.PUBLISH;

            //是否是主播端，false和默认观看端
            gsFastConfig.setPublish(isPublishMode);
            gsFastConfig.setPublishScreenMode(defPubScreenMode);
            gsFastConfig.setWatchScreenMode(defWatchScreenMode);
            gsFastConfig.setHardEncode(defPubHardEncode);
            gsFastConfig.setPubQuality(defQuality);
            gsFastConfig.setPubRatio(defRatio);
            //配置观看端打赏固定金额面板,最多支持6个固定金额,固定金额最高不能超过200000(即2000.00元)
            gsFastConfig.setFixedMoneyArray(arr);
            gsFastConfig.setShowPIP(getBooleanFromPrefrences(SettingActivity.GS_PIP));
            gsFastConfig.setShowHand(getBooleanFromPrefrences(SettingActivity.GS_HAND));
            gsFastConfig.setShownetSwitch(getBooleanFromPrefrences(SettingActivity.GS_NET));
            gsFastConfig.setShowDanmuBtn(getBooleanFromPrefrences(SettingActivity.GS_DANMU));
            gsFastConfig.setShowCloseVideo(getBooleanFromPrefrences(SettingActivity.GS_CLOSE_VIDEO));
            gsFastConfig.setSkinType(getIntFromPrefrences(SettingActivity.GS_SKIN));
            gsFastConfig.setShowCameraSwitch(getBooleanFromPrefrences(SettingActivity.GS_CAMERA_SWITCH));
            int pubScreenMode = gsFastConfig.getPublishScreenMode();

            if (gsFastConfig.isPublish() && (pubScreenMode == GSFastConfig.PUB_SCREEN_MODE_VIDEO_AND_DOC
                    || pubScreenMode == GSFastConfig.PUB_SCREEN_MODE_G_LANDSCAPE
                    || pubScreenMode == GSFastConfig.PUB_SCREEN_MODE_G_PORTRAIT)) {
                //g直播三种发布模式
                joinGlive(gsFastConfig,initParam);
            } else {
                //FastSDK 观看与发布模式
                GenseeLive.startLive(MainActivity.this, gsFastConfig, initParam);
            }
        }
//		showDuration();
    }

    private void addGSMoreItem(GSFastConfig gsFastConfig) {
        //自定义按钮，一项一个按钮，分别配置图标、文字和事件回调  需要则照样子增加
        //分屏的图标最大为20dp*20dp
        //index设置代表的含义,0-5表示需要将该item放在第一位
        //6-10表示需要将该item放在第二位
        //11-15表示需要将该item放在第三位
        //15之后表示该item放在内部默认item之后
        GSMoreItem moreItem1 = new GSMoreItem(getResources().getDrawable(R.drawable.icon_more_share), new GSMoreItem.IGSItemClickEvent() {
            @Override
            public void itemEvent(View v, String subject, String liveId) {
                toastClickView("分享", subject, liveId);
            }
        });
        moreItem1.setText("分享"); //有文字的按钮 需要设置有效的文字文本
        moreItem1.setItemIndex(1);
        Drawable drawable = getResources().getDrawable(R.drawable.ic_more_report2);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            drawable.setTint(Color.parseColor("#000000"));
        }
        GSMoreItem moreItem2 = new GSMoreItem(drawable, new GSMoreItem.IGSItemClickEvent() {
            @Override
            public void itemEvent(View v, String subject, String liveId) {
                toastClickView("举报", subject, liveId);
            }
        });
        moreItem2.setText("举报"); //有文字的按钮 需要设置有效的文字文本
        moreItem2.setItemIndex(17);
        gsFastConfig.addExtraMoreItem(moreItem1);
        gsFastConfig.addExtraMoreItem(moreItem2);
    }

    private void toastClickView(String text, String subject, String liveId) {
        Toast.makeText(MainActivity.this, text + "被点击了\n"
                + "subject=" + subject + "\nliveId=" + liveId, Toast.LENGTH_SHORT).show();
    }

    private Marquee.Speed getSpeedFromPrefrences() {
        Marquee.Speed speed = Marquee.Speed.ONE;
        int saveSpeed = preferences.getInt(SettingActivity.GS_MARQUEE_SPEED, 1);
        switch (saveSpeed) {
            case 1:
                speed = Marquee.Speed.ONE;
                break;
            case 2:
                speed = Marquee.Speed.TWO;
                break;
            case 3:
                speed = Marquee.Speed.THREE;
                break;
            case 4:
                speed = Marquee.Speed.FOUR;
                break;
            case 5:
                speed = Marquee.Speed.FIVE;
                break;
        }
        return speed;
    }

    private boolean getBooleanFromPrefrences(String key) {
        return preferences.getBoolean(key, true);
    }

    private int getIntFromPrefrences(String key) {
        return preferences.getInt(key, 0);
    }

    private String getStringFromPrefrences(String key) {
        return preferences.getString(key, "");
    }



	/*private void showDuration(){
		btnDownload.postDelayed(new Runnable() {
			@Override
			public void run() {
				String text = null;
				long time = -1;
				if(liveMode == LIVEMODE.VOD){
					time = PlayTime.getIns().getPlayTime(PlayTime.TIME_MODE_VOD);
				}else if(liveMode == LIVEMODE.WATCH){
					time = PlayTime.getIns().getPlayTime(PlayTime.TIME_MODE_LIVE_WATCH);
				}
				if(time != -1){

					Toast.makeText(getApplicationContext(),"播放时长：" + time/1000 + "秒",Toast.LENGTH_SHORT).show();
				}


				btnDownload.postDelayed(this,10000);
			}
		},10000);
	}*/



    private void configSpinner(Spinner spinner, List<String> asList, MyItemSelectedListener listener) {
        final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, asList);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                                       int arg2, long arg3) {
                if (null != listener) {
                    listener.onItemSelected(arg2);
                }
            }

            public void onNothingSelected(AdapterView<?> arg0) {
            }
        });
    }

    private interface MyItemSelectedListener {
        void onItemSelected(int position);
    }

    private void joinGlive(GSFastConfig config, InitParam initParam){
        int pubScreenMode = config.getPublishScreenMode();
        //G直播3种发布端模式
		if (config.isPublish() && (pubScreenMode == GSFastConfig.PUB_SCREEN_MODE_VIDEO_AND_DOC
				|| pubScreenMode == GSFastConfig.PUB_SCREEN_MODE_G_LANDSCAPE
				|| pubScreenMode == GSFastConfig.PUB_SCREEN_MODE_G_PORTRAIT)) {
			//G直播发布端
			GSLiveConfig gsLiveConfig = new GSLiveConfig();
			if (pubScreenMode == GSFastConfig.PUB_SCREEN_MODE_VIDEO_AND_DOC) {
				gsLiveConfig.setLiveMode(LiveMode.PUBLISH_VIDEO_DOC);
			} else if (pubScreenMode == GSFastConfig.PUB_SCREEN_MODE_G_LANDSCAPE) {
				gsLiveConfig.setLiveMode(LiveMode.PUBLISH_PURE_VIDEO_LANDSCAPE);
			} else if (pubScreenMode == GSFastConfig.PUB_SCREEN_MODE_G_PORTRAIT) {
				gsLiveConfig.setLiveMode(LiveMode.PUBLISH_PURE_VIDEO_PORTRAIT);
			}
			int quality = config.getPubQuality();
			PublishVideoQuality gQuality = PublishVideoQuality.QUALITY_HIGH;
			if (quality == GSFastConfig.PUB_QUALITY_HD) {
				gQuality = PublishVideoQuality.QUALITY_MIDDLE;
			} else if (quality == GSFastConfig.PUB_QUALITY_SD) {
				gQuality = PublishVideoQuality.QUALITY_LOW;
			}
			PublishVideoRatio ratio = config.getPubRatio() == GSFastConfig.PUB_RATIO_4_TO_3 ? PublishVideoRatio.RATIO_4_3 : PublishVideoRatio.RATIO_16_9;
			gsLiveConfig.setPublishVideoConfig(new PublishVideoConfig().setVideoQuality(gQuality).
					setHardEncode(config.isHardEncode()).
					setPublishVideoRatio(ratio));
			GSLiveSDK.join(this,initParam,gsLiveConfig);
		}
    }


}
