package com.gensee.fragement;

import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.Toast;

import com.gensee.common.GenseeConfig;
import com.gensee.common.ServiceType;
import com.gensee.config.ConfigApp;
import com.gensee.entity.InitParam;
import com.gensee.playerdemo.PlayerDemoActivityEx;
import com.gensee.playerdemo.R;
import com.gensee.utils.GenseeLog;
import com.gensee.voddemo.VodActivity;

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

public class InitParamFragment extends Fragment implements OnClickListener{
	private static final String TAG = "JoinInfoFragment";
	private EditText mEditDomain;
	private EditText mEditNumber;
	private EditText mEidtAccount;
	private EditText mEidtAccountPwd;
	private EditText mEditNickName;
	private EditText mEditK;
	private Spinner mSpinner;
	private Spinner mSpinnerPlayType;
	private EditText mEditJoinPwd;
	private EditText mEditUserId;
	private EditText mEditGroupId;
	/**
	 * box 客户使用自定义端口的情况下设置，一般情况下不用设置
	 */
	private EditText mEditHttpPort,mEditWsPort;
	private View linPort;
	private Button mBtnJoin;
	private Switch rbMutePlay;
	private ServiceType serviceType = ServiceType.WEBCAST;
	private SharedPreferences preferences;
	
	private String playType = ConfigApp.PLAY_LIVE;//直播/点播
	private static final String EXTRA = "_vod";
	
	
	public InitParamFragment(){
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		GenseeLog.i(TAG, "onCreate");
		preferences = getActivity().getSharedPreferences(ConfigApp.PREFERENCED, Context.MODE_PRIVATE);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {
		GenseeLog.i(TAG, "onCreateView");
		
		View v = inflater.inflate(R.layout.login, null);
		linPort = v.findViewById(R.id.linPort);
		mEditDomain = (EditText) v.findViewById(R.id.gs_domin);
		mEditNumber = (EditText) v.findViewById(R.id.gs_numble);
		mEidtAccount = (EditText) v.findViewById(R.id.gs_account);
		mEidtAccountPwd = (EditText) v.findViewById(R.id.gs_account_psw);
		mEditNickName = (EditText) v.findViewById(R.id.gs_nickroom);
		mEditJoinPwd = (EditText) v.findViewById(R.id.gs_nickname_psw);
		mEditK = (EditText) v.findViewById(R.id.editK);
		mEditUserId = (EditText) v.findViewById(R.id.editUid);
		mEditGroupId = v.findViewById(R.id.gs_edit_groupId);
		mEditHttpPort = linPort.findViewById(R.id.gs_edit_httpPort);
		mEditWsPort = linPort.findViewById(R.id.gs_edit_wsPort);
		mSpinner = (Spinner) v.findViewById(R.id.Spinner01);
		mSpinnerPlayType = (Spinner) v.findViewById(R.id.SpinnerPlayType);
		mBtnJoin = (Button) v.findViewById(R.id.gs_bnt_room_join);
		rbMutePlay = (Switch) v.findViewById(R.id.rb_mutePlay);
		mBtnJoin.setOnClickListener(this);
		bindPlayType(preferences);

//		testFixedParamJoin();
		return v;
	}

	/**
	 * 写死固定参数加会
	 */
	private void testFixedParamJoin() {
		mEditDomain.setText("cjl.gensee.com");
		mEditNumber.setText("408N0sjq79");
		mEditNickName.setText("tester");
		playType = ConfigApp.PLAY_VOD;
		serviceType = ServiceType.TRAINING;
		onClick(mBtnJoin);
	}

	public void bindPlayType(final SharedPreferences preferences){
		GenseeLog.i(TAG, "bindData");
		
	
		List<String> listPlayTypes = new ArrayList<String>();
		listPlayTypes.add(ConfigApp.PLAY_LIVE);
		listPlayTypes.add(ConfigApp.PLAY_VOD);

		ArrayAdapter<String> adapterPt = new ArrayAdapter<String>(getActivity(),
				R.layout.spinner_layout, listPlayTypes);
		adapterPt.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		mSpinnerPlayType.setAdapter(adapterPt);
		mSpinnerPlayType.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> arg0, View arg1,
									   int arg2, long arg3) {
				switch (arg2) {
					case 0:
						playType = ConfigApp.PLAY_LIVE;
						bindData(preferences, "");
						mEditGroupId.setVisibility(View.VISIBLE);
						linPort.setVisibility(View.VISIBLE);
						break;
					case 1:
						playType = ConfigApp.PLAY_VOD;
						bindData(preferences, EXTRA);
						mEditGroupId.setVisibility(View.GONE);
						linPort.setVisibility(View.GONE);
						break;
				}
			}

			public void onNothingSelected(AdapterView<?> arg0) {
			}
		});
		playType = preferences.getString(ConfigApp.PARAMS_PLAY_TYPE, ConfigApp.PLAY_VOD);
		mSpinnerPlayType.setSelection(ConfigApp.PLAY_LIVE.equals(playType)?0:1);
		rbMutePlay.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				ConfigApp.mutePlay = isChecked;
			}
		});
	}
	private void bindData(SharedPreferences preferences,String extra){
		String defDomain = "";
		String defNumber = "";
		String defNickName = "";
		String defJoinPwd = "";
		String defUserId = "";
		String defK = "";
		String defGroupId = "";
		String defHttpPort="";
		String defWebSocketPort="";

		mEditDomain.setText(preferences.getString(ConfigApp.PARAMS_DOMAIN
				+ extra, defDomain));
		mEditNumber.setText(preferences.getString(ConfigApp.PARAMS_NUMBER
				+ extra, defNumber));
		mEidtAccount.setText(preferences.getString(ConfigApp.PARAMS_ACCOUNT
				+ extra, ""));
		mEidtAccountPwd.setText(preferences.getString(ConfigApp.PARAMS_PWD
				+ extra, ""));
		mEditNickName.setText(preferences.getString(ConfigApp.PARAMS_NICKNAME
				+ extra, defNickName));
		mEditJoinPwd.setText(preferences.getString(ConfigApp.PARAMS_JOINPWD
				+ extra, defJoinPwd));
		mEditUserId.setText(preferences.getString(ConfigApp.PARAMS_USERID
				+ extra, defUserId));
		mEditK.setText(preferences.getString(ConfigApp.PARAMS_K
				+ extra, defK));
		mEditGroupId.setText(preferences.getString(ConfigApp.PARAMS_GROUPID
				+ extra, defGroupId));
		mEditHttpPort.setText(preferences.getString(ConfigApp.PARAMS_HTTP_PORT
				+ extra, defHttpPort));
		mEditWsPort.setText(preferences.getString(ConfigApp.PARAMS_WEBSOCKET_PORT
				+ extra, defWebSocketPort));
		List<String> list = new ArrayList<String>();
		list.add(getString(R.string.webcast_type));
		list.add(getString(R.string.training_type));
		final ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
				R.layout.spinner_layout, list);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		mSpinner.setAdapter(adapter);
		mSpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				switch (arg2) {
				case 0:
					serviceType = ServiceType.WEBCAST;
					break;
				case 1:
					serviceType = ServiceType.TRAINING;
					break;
				}
			}

			public void onNothingSelected(AdapterView<?> arg0) {
			}
		});
		String service = preferences.getString(ConfigApp.PARAMS_SERVICE
				+ extra, ServiceType.WEBCAST.getValue());
		mSpinner.setSelection(ServiceType.WEBCAST.getValue().equals(service)?0:1);
	}
	
	
    public void saveData(SharedPreferences preferences){
    	String domain = mEditDomain.getText().toString();
		String number = mEditNumber.getText().toString();
		String account = mEidtAccount.getText().toString();
		String accountPwd = mEidtAccountPwd.getText().toString();
		String joinPwd = mEditJoinPwd.getText().toString();
		String nickName = mEditNickName.getText().toString();
		String kValue = mEditK.getText().toString();
		String userId = mEditUserId.getText().toString();
		String groupId = mEditGroupId.getText().toString();
		String httpPort = mEditHttpPort.getText().toString();
		String websocketPort = mEditWsPort.getText().toString();

		String kDomain = ConfigApp.PARAMS_DOMAIN;
		String kNumber = ConfigApp.PARAMS_NUMBER;
		String kAcc = ConfigApp.PARAMS_ACCOUNT;
		String kPWD = ConfigApp.PARAMS_PWD;
		String kNickName = ConfigApp.PARAMS_NICKNAME;
		String kJoinPwd = ConfigApp.PARAMS_JOINPWD;
		String kK = ConfigApp.PARAMS_K;
		String kUserId = ConfigApp.PARAMS_USERID;
		String kService = ConfigApp.PARAMS_SERVICE;
		String kGroupId = ConfigApp.PARAMS_GROUPID;
		String kHttpPort = ConfigApp.PARAMS_HTTP_PORT;
		String kWebSocketPort = ConfigApp.PARAMS_WEBSOCKET_PORT;
		if (ConfigApp.PLAY_VOD.equals(playType)) {
			kDomain += EXTRA;
			kNumber += EXTRA;
			kAcc += EXTRA;
			kPWD += EXTRA;
			kNickName += EXTRA;
			kJoinPwd += EXTRA;
			kK += EXTRA;
			kService += EXTRA;
			kUserId += EXTRA;
			kGroupId += EXTRA;
		}
		
		preferences.edit().putString(ConfigApp.PARAMS_PLAY_TYPE, playType)
				.putString(kService, serviceType.getValue())
				.putString(kDomain, domain)
				.putString(kNumber, number)
				.putString(kAcc, account)
				.putString(kPWD, accountPwd)
				.putString(kNickName, nickName)
				.putString(kJoinPwd, joinPwd)
				.putString(kK, kValue)
				.putString(kUserId,userId)
				.putString(kGroupId,groupId)
				.putString(kHttpPort,httpPort)
				.putString(kWebSocketPort,websocketPort)
				.commit();

    }
    
    
    

	@Override
	public void onClick(View v) {
		InitParam p = getInitParam();
		if (p != null) {
			saveData(preferences);
			ConfigApp.getIns().setInitParam(p);
			Intent i = new Intent();
			if (ConfigApp.PLAY_LIVE.equals(playType)) {
				i.setClass(getActivity(), PlayerDemoActivityEx.class);
			} else {
				i.setClass(getActivity(), VodActivity.class);
			}
			getActivity().startActivity(i);
		}
	}

	public 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();
		String groupId = mEditGroupId.getText().toString();
		String httpPort = mEditHttpPort.getText().toString();
		String websocketPort = mEditWsPort.getText().toString();
		if ("".equals(domain) || "".equals(number)||"".equals(nickName)) {
			toastMsg("域名/编号/昵称 都不能为空");
			return null;
		}

		InitParam initParam = new InitParam();
		// 设置域名
		initParam.setDomain(domain);
		if (number.length() == 8 && isNumber(number)) {//此判断是为了测试方便，请勿模仿，实际使用时直接使用其中一种设置
			// 设置编号,8位数字字符串，
			initParam.setNumber(number);
		} else {
			// 如果只有直播间/点播id（混合字符串
			// 如：8d5261f20870499782fb74be021a7e49）可以使用setLiveId("")代替setNumber()
			String liveId = number;
			initParam.setLiveId(liveId);
		}
		// 设置站点登录帐号（根据配置可选）
		initParam.setLoginAccount(account);
		// 设置站点登录密码（根据配置可选）
		initParam.setLoginPwd(pwd);
		// 设置显示昵称 不能为空,请传入正确的昵称，有显示和统计的作用
		// 设置显示昵称，如果设置为空，请确保
		initParam.setNickName(nickName);
		// 设置加入口令（根据配置可选）
		initParam.setJoinPwd(joinPwd);
		// 设置服务类型，如果站点是webcast类型则设置为ServiceType.ST_CASTLINE，
		// training类型则设置为ServiceType.ST_TRAINING
		initParam.setServiceType(serviceType);
		//如果有想传入自己的用户id，请保证满足条件，即自定义用户id
		if (userId.length() > 0) {
			long lUserId = Long.valueOf(userId);
			if (lUserId > 1000000000) {
				initParam.setUserId(lUserId);//大于1000000000有效
			}
		}
		//如果启用第三方认证，k必填项，且要正确有效
		//站点 系统设置 的 第三方集成 中直播模块 “认证“  启用时请确保”第三方K值“（你们的k值）的正确性 ；如果没有启用则忽略这个参数
		initParam.setK(k);
		//双师课堂有分组的情况下必须传入一个分组id，表示本次是加到课堂后属于该分组
		initParam.setGroupCode(groupId);
//		initParam.setUserData("vip=1&city=上海");
		//端口设置，一般情况下使用非  xxx.gensee.com 的站点可能会用到，90%以上的情况不需要设置
		if (httpPort.length() > 0) {
			try {
				initParam.setHttpPort( Short.valueOf(httpPort));
			}catch (NumberFormatException e){
				e.printStackTrace();
			}
		}
		if (websocketPort.length() > 0) {
			try {
				initParam.setWebsocketPort(Short.valueOf(websocketPort));
			} catch (NumberFormatException e) {
				e.printStackTrace();
			}
		}
		return initParam;
	}
	
	private void toastMsg(String msg) {
		Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
	}

	private boolean isNumber(String number) {
		try {
			Long.parseLong(number);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	
}
