package com.gensee.playerdemo;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.gensee.common.ServiceType;
import com.gensee.entity.InitParam;

import java.util.ArrayList;

/**
 * author : guohaonan
 * date : 2023/8/23 15:15
 * description :
 */
public class MutiLiveParamActivity extends Activity {

    private EditText editDomain, editNum, editAccount, editLoginPwd,
            editNickName, editJoinPwd, editThirdK, edtGroupCode,edtCacheNum,edtPreloadNum;

    private Spinner spinnerService;//webcast or training
    private SharedPreferences preferences;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_videos);
        preferences = getPreferences(MODE_PRIVATE);
        editDomain = (EditText) findViewById(R.id.editDomain);
        editNum = (EditText) findViewById(R.id.editNum);
        editAccount = (EditText) findViewById(R.id.editAccount);
        editLoginPwd = (EditText) findViewById(R.id.editLoginPwd);
        editNickName = (EditText) findViewById(R.id.editNickName);
        editJoinPwd = (EditText) findViewById(R.id.editJoinPwd);
        editThirdK = (EditText) findViewById(R.id.editK);
        edtCacheNum = (EditText) findViewById(R.id.cache_num);
        edtPreloadNum = (EditText) findViewById(R.id.preload_num);
        edtGroupCode = findViewById(R.id.editGroupCode);

        //Webcast,Training
        String[] services = new String[] {
                ServiceType.WEBCAST.getValue(),
                ServiceType.TRAINING.getValue()
        };
        spinnerService = (Spinner) findViewById(R.id.spinnerService);
        spinnerService.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, services));
        spinnerService.setSelection(0);
//        spinnerService.setOnItemSelectedListener(this);

        findViewById(R.id.btnGo).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                InitParam baseParam = initBaseParam();
                if (baseParam == null) {
                    return;
                }

                String numberStr = editNum.getText().toString().trim();
                String joinPwd= editJoinPwd.getText().toString().trim();
                if (numberStr.isEmpty()) {
                    toast("编号不能为空");
                    return;
                }
                String[] numberSplit = numberStr.split(",");
                String[] pwSplit = null;
                if (!joinPwd.isEmpty()) {
                    pwSplit = joinPwd.split(",");
                    if (numberSplit.length != pwSplit.length) {
                        toast("编号和口令数量不匹配");
                        return;
                    }
                }
                // 底层sdk缓存点播件数量，建议为10
                int cacheNum = Integer.parseInt(edtCacheNum.getText().toString());
                // viewPager预加载数量
                int preloadNum = Integer.parseInt(edtPreloadNum.getText().toString());
                if (cacheNum == 0 || preloadNum == 0) {
                    toast("缓存数量不能为0");
                    return;
                }
                // 实际使用过程中，整个app内活跃的VodPlayer对象不要超过GenseeConfig.vodCacheCount的值
                // 建议最大实例数不超过10，最好为3～4
                // 在此demo中，使用的时viewpager，所以预缓存+2为最大实例数
                if (preloadNum + 2 > cacheNum) {
                    toast("实例数超过了缓存数");
                    return;
                }

                // 24433313,85946754,00080214,87957144,29436879,05220242,98651557,39840100,82040835,87217444,94782256,04635404,77583062,25238254,82315546,22524767
                ArrayList<InitParam> paramsList = createParamsList(baseParam, numberSplit, pwSplit);
                if (!paramsList.isEmpty()) {

                    preferences.edit()
                            .putString("muti_live_domain", baseParam.getDomain())
                            .putString("muti_live_number" , numberStr)
                            .putString("muti_live_account" , baseParam.getLoginAccount())
                            .putString("muti_live_accPwd" , baseParam.getLoginPwd())
                            .putString("muti_live_nickname" , baseParam.getNickName())
                            .putString("muti_live_joinPwd" , joinPwd)
                            .putString("muti_live_groupCode" , baseParam.getGroupCode())
                            .putInt("muti_live_serviceIndex" , spinnerService.getSelectedItemPosition())
                            .putInt("muti_cache_num" , cacheNum)
                            .putInt("muti_preload_num" , preloadNum)
                            .commit();

                    Intent intent = new Intent(MutiLiveParamActivity.this, WaterfallActivity.class);
                    intent.putExtra("paramsList",paramsList);
                    intent.putExtra("preloadNum",preloadNum);
                    startActivity(intent);
                }
            }
        });

        bindData();
    }

    private ArrayList<InitParam> createParamsList(InitParam baseParam, String[] numberSplit, String[] pwSplit) {
        ArrayList<InitParam> paramList = new ArrayList<>();
        for (int i = 0; i < numberSplit.length; i++) {
            try {
                String number = numberSplit[i];
                InitParam clone = baseParam.clone();
                //编号或id必需至少要有一个
                if (number.length() == 8) {//方便测试，不要模仿，实际代码选择一个分支即可
                    // 直播或点播编号
                    clone.setNumber(number);
                } else {
                    //直播id或点播id
                    String liveId = number;
                    clone.setLiveId(liveId);
                }

                //如果后台设置了密码(口令)，必须传入正确的密码
                if (pwSplit != null) {

                    clone.setJoinPwd(pwSplit[i]);
                }
                paramList.add(clone);
            } catch (CloneNotSupportedException e) {
                e.printStackTrace();
            }
        }
        return paramList;
    }

    private void bindData(){
        String domain = preferences.getString("muti_live_domain", "");
        String number = preferences.getString("muti_live_number", "");
        String account = preferences.getString("muti_live_account", "");
        String accPwd = preferences.getString("muti_live_accPwd", "");
        String nickName = preferences.getString("muti_live_nickname", "");
        String joinPwd = preferences.getString("muti_live_joinPwd", "");
        String groupCode = preferences.getString("muti_live_groupCode", "");
        int serviceIndex = preferences.getInt("muti_live_serviceIndex", 0);
        int cacheNum = preferences.getInt("muti_cache_num", 10);
        int preloadNum = preferences.getInt("muti_preload_num", 3);
        editDomain.setText(domain);
        editNum.setText(number);
        editAccount.setText(account);
        editLoginPwd.setText(accPwd);
        editNickName.setText(nickName);
        editJoinPwd.setText(joinPwd);
        spinnerService.setSelection(serviceIndex);
        edtGroupCode.setText(groupCode);
        edtCacheNum.setText(cacheNum +"");
        edtPreloadNum.setText(preloadNum+"");
    }


    private InitParam initBaseParam(){
        String domain = editDomain.getText().toString().trim();

        String account = editAccount.getText().toString().trim();
        String loginPwd = editLoginPwd.getText().toString().trim();
        String nickName = editNickName.getText().toString().trim();

        String k = editThirdK.getText().toString().trim();
        String groupCode = edtGroupCode.getText().toString().trim();

        if ("".equals(domain)) {
            toast("域名不能为空");
            return null;
        }
        if("".equals(nickName)){
            toast("昵称不能为空");
            return null;
        }
        InitParam mInitParam = new InitParam();
        //站点域名 如：demo.gensee.com 必需
        mInitParam.setDomain(domain);

        //站点登录帐号，后台勾选需要登录的话一定传入正确的帐号
        mInitParam.setLoginAccount(account);
        //站点登录密码，后台勾选需要登录的话一定传入正确的密码
        mInitParam.setLoginPwd(loginPwd);
        //昵称，必需
        mInitParam.setNickName(nickName);

        //如果后台启用了第三方认证，必须传入正确的K值
        mInitParam.setK(k);
        //必须选择一种 serviceType
        // 站点类型ServiceType.ST_CASTLINE 直播webcast，
        // ServiceType.ST_TRAINING 培训 training
        if (spinnerService.getSelectedItemPosition() == 0) {
            mInitParam.setServiceType(ServiceType.WEBCAST);
        } else {
            mInitParam.setServiceType(ServiceType.TRAINING);
        }

        mInitParam.setGroupCode(groupCode);
        //设置第三方的用户id  > 1000000000 (10亿)有效
//		mInitParam.setUserId(userId);
        //对点播有效，如果是下载则填入true，如果是在线播放填入false
//		mInitParam.setDownload(true);

        //mInitParam.setUserData("电话=123&公司=展视互动");


        return mInitParam;

    }


    public void toast(final String msg){
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
            }
        });
    }
}
