package com.baidu.rtc.sample.data;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.AudioAttributes;
import android.media.MediaRecorder;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;

import com.baidu.rtc.RtcParameterSettings;
import com.baidu.rtc.audio.BRTCAudioScenario;
import com.baidu.rtc.sample.R;
import com.baidu.rtc.sample.util.JavaTypesHelper;
import com.baidu.rtc.sample.util.Utils;

public class RtcClientData implements Parcelable {
    private static final String TAG = RtcClientData.class.getSimpleName();

    public String mAppId = "";
    public String mTokenStr = "";
    public String mUserId = "";
    public String mUserName = "";
    public String mRoomName = "";
    public String mMediaServer = "";
    public String mMediaServerIP = "";
    public String mVideoResolution = "";
    public String mScreenResolution;
    public String mScreenFps = "10";
    public String mVideoFps = "15";
    public String mVideoBitrate = "0";
    public String mVideoMinBitrate = "0";
    public String mVideoCodec = RtcParameterSettings.VideoCodecId.H264;
    public String mVideoDegradationPreference = "";
    public boolean mEnableHighProfile = false;

    public String mRtmpUrl = "";
    public boolean mRtmpMix = false;
    public boolean mRecording = false;
    public String mRtmpTemplate = "";
    public String mRtmpMode = "0";

    public String networkPolicy = "";
    public String keyAgreenent = "";
    public String audioProfile = "";
    public String audioScenario = "";

    public boolean mEnableScreenAudio = false;

    public boolean isBigRoomMode = false;

    public boolean mAudioOnly = false;
    public boolean mNoiseCancellation = false;
    public boolean mEchoCancllation = false;
    public boolean mVocalGain = false;
    public boolean mEnableMultistream = true;
    public boolean mHasRemoteAudio = true;
    public boolean mHasRemoteVideo = true;
    public @com.baidu.rtc.model.Constants.SubscribeMode
    int subscribeMode = com.baidu.rtc.model.Constants.SubscribeMode.MANUAL_MODE;
    public int maxSubscriberCount = 3;
    public int transportMode = RtcParameterSettings.RtcSignalChannelMode.RTC_SIGNAL_CHANNEL_MODE_TCP.ordinal();

    public boolean mHasDataChannel = false;
    public boolean mOnlineOpen = true;
    public boolean mAutoSubscribe = false;
    public boolean mAutoPublish = true;

    public boolean mEnablePruneSignal = false;
    public boolean mFixResolution = false;
    public boolean mAutoReconnect = true;
    public boolean mEnableVideoPullDemote = false;
    public boolean enableBeauty = false;
    /**
     * 是否采集本地录制音频到本地文件
     */
    public boolean mEnableLocalCaptureAudioDump = false;
    public boolean mEnableMixAudioDump = false;

    /** 通过checkData 函数进行赋值, 不是直接从Intent 读取 */
    public int mWeakNetworkPolicy = 1;
    public int mKeyAggrementProtocol = 0;
    public int mAudioQuality = Constants2.AudioQuality.AUDIO_QUALITY_HD;
    public int mAudioScenario = BRTCAudioScenario.BRTC_AUDIO_SCENARIO_SPEECH.getValue();

    public boolean mIsWatch = false;

    public RtcClientData() {
    }
    protected RtcClientData(Parcel in) {
        mAppId = in.readString();
        mTokenStr = in.readString();
        mUserId = in.readString();
        mUserName = in.readString();
        mRoomName = in.readString();
        mMediaServer = in.readString();
        mMediaServerIP = in.readString();
        mScreenResolution = in.readString();
        mScreenFps = in.readString();
        mRtmpUrl = in.readString();
        mRtmpMix = in.readByte() != 0;
        mRecording = in.readByte() != 0;
        mRtmpTemplate = in.readString();
        mRtmpMode = in.readString();

        networkPolicy = in.readString();
        keyAgreenent = in.readString();
        audioProfile = in.readString();
        audioScenario = in.readString();

        mVideoFps = in.readString();
        mVideoBitrate = in.readString();
        mVideoMinBitrate = in.readString();
        mVideoResolution = in.readString();
        mVideoCodec = in.readString();
        mVideoDegradationPreference = in.readString();
        mEnableHighProfile = in.readByte() != 0;

        mEnableScreenAudio = in.readByte() != 0;
        isBigRoomMode = in.readByte() != 0;

        mAudioOnly = in.readByte() != 0;
        mNoiseCancellation = in.readByte() != 0;
        mEchoCancllation = in.readByte() != 0;
        mVocalGain = in.readByte() != 0;
        mEnableMultistream = in.readByte() != 0;

        mHasRemoteAudio = in.readByte() != 0;
        mHasRemoteVideo = in.readByte() != 0;

        mHasDataChannel = in.readByte() != 0;
        mOnlineOpen = in.readByte() != 0;
        mAutoSubscribe = in.readByte() != 0;
        mAutoPublish = in.readByte() != 0;

        enableBeauty = in.readByte() != 0;

        subscribeMode = in.readInt();
        maxSubscriberCount = in.readInt();
        transportMode = in.readInt();

        mEnableVideoPullDemote = in.readByte() != 0;
        mAutoReconnect = in.readByte() != 0;
        mFixResolution = in.readByte() != 0;
        mEnablePruneSignal = in.readByte() != 0;
        mEnableLocalCaptureAudioDump = in.readByte() != 0;
        mEnableMixAudioDump = in.readByte() != 0;
        mIsWatch = in.readByte() != 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(mAppId);
        dest.writeString(mTokenStr);
        dest.writeString(mUserId);
        dest.writeString(mUserName);
        dest.writeString(mRoomName);
        dest.writeString(mMediaServer);
        dest.writeString(mMediaServerIP);
        dest.writeString(mScreenResolution);
        dest.writeString(mScreenFps);
        dest.writeString(mRtmpUrl);
        dest.writeByte((byte) (mRtmpMix ? 1 : 0));
        dest.writeByte((byte) (mRecording ? 1 : 0));
        dest.writeString(mRtmpTemplate);
        dest.writeString(mRtmpMode);

        dest.writeString(networkPolicy);
        dest.writeString(keyAgreenent);
        dest.writeString(audioProfile);
        dest.writeString(audioScenario);

        dest.writeString(mVideoFps);
        dest.writeString(mVideoBitrate);
        dest.writeString(mVideoMinBitrate);
        dest.writeString(mVideoResolution);
        dest.writeString(mVideoCodec);
        dest.writeString(mVideoDegradationPreference);
        dest.writeByte((byte) (mEnableHighProfile ? 1 : 0));

        dest.writeByte((byte) (mEnableScreenAudio ? 1 : 0));
        dest.writeByte((byte) (isBigRoomMode ? 1 : 0));

        dest.writeByte((byte) (mAudioOnly ? 1 : 0));
        dest.writeByte((byte) (mNoiseCancellation ? 1 : 0));
        dest.writeByte((byte) (mEchoCancllation ? 1 : 0));
        dest.writeByte((byte) (mVocalGain ? 1 : 0));
        dest.writeByte((byte) (mEnableMultistream ? 1 : 0));

        dest.writeByte((byte) (mHasRemoteAudio ? 1 : 0));
        dest.writeByte((byte) (mHasRemoteVideo ? 1 : 0));

        dest.writeByte((byte) (mHasDataChannel ? 1 : 0));
        dest.writeByte((byte) (mOnlineOpen ? 1 : 0));
        dest.writeByte((byte) (mAutoSubscribe ? 1 : 0));
        dest.writeByte((byte) (mAutoPublish ? 1 : 0));
        dest.writeByte((byte) (enableBeauty ? 1 : 0));

        dest.writeInt(subscribeMode);
        dest.writeInt(maxSubscriberCount);
        dest.writeInt(transportMode);

        dest.writeByte((byte) (mEnableVideoPullDemote ? 1 : 0));
        dest.writeByte((byte) (mAutoReconnect ? 1 : 0));
        dest.writeByte((byte) (mFixResolution ? 1 : 0));
        dest.writeByte((byte) (mEnablePruneSignal ? 1 : 0));
        dest.writeByte((byte) (mEnableLocalCaptureAudioDump ? 1 : 0));
        dest.writeByte((byte) (mEnableMixAudioDump ? 1 : 0));
        dest.writeByte((byte) (mIsWatch ? 1 : 0));
    }

    @Override
    public int describeContents() {
        return 0;
    }

    public static final Creator<RtcClientData> CREATOR = new Creator<RtcClientData>() {
        @Override
        public RtcClientData createFromParcel(Parcel in) {
            return new RtcClientData(in);
        }

        @Override
        public RtcClientData[] newArray(int size) {
            return new RtcClientData[size];
        }
    };

    /** 读取缓存信息 */
    public void readCacheData(Context context) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        mAppId = prefs.getString("key_appid", context.getString(R.string.baidu_rtc_app_id));
        mTokenStr = prefs.getString("key_token", context.getString(R.string.baidu_rtc_token_tmp));

        int userId = Utils.getDeviceUid();
        mUserId = prefs.getString("key_userId", String.valueOf(userId));
        if (!TextUtils.isEmpty(mUserId)) {
            try {
                SharedPreferences.Editor editor =  prefs.edit();
                editor.putString("key_userId", mUserId);
                editor.apply();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        mUserName = prefs.getString("user_display_name",
                context.getString(R.string.pref_default_display_name));
        mMediaServer = prefs.getString("key_media_server_url",
                context.getString(R.string.pref_default_media_server_url));
        mMediaServerIP = prefs.getString("key_media_server_ip", "");
        mVideoResolution = prefs.getString("video_resolution", "");
        mScreenResolution = prefs.getString("screen_resolution", "1280x720-1500kbps");
        mScreenFps = prefs.getString("screen_fps", "10");
        mRtmpUrl = prefs.getString("key_rtmp_url", "");
        mRtmpMix = prefs.getBoolean("key_rtmp_mix", false);
        mRecording = prefs.getBoolean("key_recording", false);
        mRtmpTemplate = prefs.getString("key_rtmp_template", "");
        mRtmpMode = prefs.getString("key_rtmp_mode", "0");
        networkPolicy = prefs.getString("weak_network_policy", "0");
        /** 默认使用DLTS */
        keyAgreenent = prefs.getString("key_agreement_protocol", "0");
        audioProfile = prefs.getString("key_audio_profile", "3");
        audioScenario = prefs.getString("key_audio_scenario", "1");

        mVideoFps = prefs.getString("video_fps", "15");
        mVideoBitrate = prefs.getString("video_bitrate", "0");
        mVideoMinBitrate = prefs.getString("video_min_bitrate", "0");
        mVideoCodec = prefs.getString("video_codec", "H264");
        mVideoDegradationPreference = prefs.getString("key_video_degradation_preference",
                RtcParameterSettings.RtcVideoDegradationPreference.MAINTAIN_FRAMERATE.getValue());

        mEnableHighProfile = prefs.getBoolean("key_enable_video_high_profile", false);
        mFixResolution = prefs.getBoolean("key_fixed_resolution", false);
        mAutoReconnect = prefs.getBoolean("key_re_connect", true);
        mEnableVideoPullDemote = prefs.getBoolean("key_enable_video_pull_degradation", false);

        isBigRoomMode = prefs.getBoolean("key_big_room_mode", false);
        mEnableScreenAudio = prefs.getBoolean("enable_screen_audio", false);

        mAudioOnly = prefs.getBoolean("key_audio_only", false);

        mNoiseCancellation = prefs.getBoolean("key_noise_cancellation", false);
        mEchoCancllation = prefs.getBoolean("key_echo_cancellation", false);
        mVocalGain = prefs.getBoolean("key_vocal_gain", false);
//        mEnableMultistream = prefs.getBoolean("key_enable_multistream", true);

        mHasRemoteAudio = prefs.getBoolean("key_has_remote_audio", true);
        mHasRemoteVideo = prefs.getBoolean("key_has_remote_video", true);

        mHasDataChannel = prefs.getBoolean("key_datachannel_test", false);

        mOnlineOpen = prefs.getBoolean("online_open", true);

        mAutoSubscribe = prefs.getBoolean("key_auto_subscribe_stream", true);
        mAutoPublish = prefs.getBoolean("key_auto_publish_stream", true);
        enableBeauty = prefs.getBoolean("Enable_Beauty", false);

        /** 默认选择 none模式 */
        subscribeMode = getValueIntType(prefs, "key_prune_signal_mode", 0);
        maxSubscriberCount = getValueIntType(prefs, "pref_prune_signal_subscriber_num", 3);

        transportMode = getValueIntType(prefs, "key_signal_transport_mode", 0);
        mEnablePruneSignal = subscribeMode > 0;
        mEnableLocalCaptureAudioDump = prefs.getBoolean("key_dump_capturer_audio", false);
        mEnableMixAudioDump = prefs.getBoolean("key_dump_mix_audio", false);

        checkData(context);
    }

    public void checkData(Context context) {
        if (!TextUtils.isEmpty(networkPolicy)) {
            try {
                mWeakNetworkPolicy = Integer.valueOf(networkPolicy);
            } catch (NumberFormatException e) {
                Log.e(TAG, e.getMessage());
            }
        }
        if (!TextUtils.isEmpty(keyAgreenent)) {
            try {
                mKeyAggrementProtocol = Integer.valueOf(keyAgreenent);
            } catch (NumberFormatException e) {
                Log.e(TAG, e.getMessage());
            }
        }

        if (!TextUtils.isEmpty(audioProfile)) {
            try {
                mAudioQuality = Integer.valueOf(audioProfile);
            } catch (NumberFormatException e) {
                Log.e(TAG, e.getMessage());
            }
        }

        if (!TextUtils.isEmpty(audioProfile)) {
            try {
                mAudioScenario = Integer.valueOf(audioScenario);
            } catch (NumberFormatException e) {
                Log.e(TAG, e.getMessage());
            }
            if (mAudioScenario < BRTCAudioScenario.values()[0].getValue()
                    || mAudioScenario > BRTCAudioScenario.values()[BRTCAudioScenario.values().length - 1]
                    .getValue()) {
                mAudioScenario = BRTCAudioScenario.BRTC_AUDIO_SCENARIO_DEFAULT.getValue();
            }
        }

        if (TextUtils.isEmpty(mMediaServer)) {
            mMediaServer = context.getString(R.string.pref_default_media_server_url);
        }

        if (TextUtils.isEmpty(mMediaServerIP)) {
            mMediaServerIP = "";
        }

        if (TextUtils.isEmpty(mRoomName)) {
            mRoomName = context.getString(R.string.pref_default_room_name);
        }
        if (TextUtils.isEmpty(mAppId)) {
            mAppId = context.getString(R.string.baidu_rtc_app_id);
        }
        updateVideoWidthHeight();
    }
    public int videoHeight = 640;
    public int videoWidth = 360;
    public void updateVideoWidthHeight() {
        if (!TextUtils.isEmpty(mVideoResolution)) {
            String res = mVideoResolution;
            try {
                String[] arr = res.split("\\(")[0].split("x");
                videoHeight = Integer.valueOf(arr[0]);
                videoWidth = Integer.valueOf(arr[1]);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (videoHeight > 8192 || videoWidth > 4320) {
            videoHeight = 8192;
            videoWidth = 4320;
        }
    }

    public RtcClientData createNewOne(Context context) {
        Intent intent = new Intent();
        intent.putExtra("data", this);
        RtcClientData data = intent.getExtras().getParcelable("data");
        data.checkData(context);
        return data;
    }

    public void updateParamsSettings(RtcParameterSettings cfg) {
        // server
        cfg.MediaServerIP = mMediaServerIP;
        // 帧率
        cfg.VideoFps = JavaTypesHelper.toInt(mVideoFps, 15);
        cfg.subscribeMode = subscribeMode;
        /** 默认最多订阅4人 */
        cfg.subscribeMaxCount = 4;
        if (maxSubscriberCount > 0 && maxSubscriberCount < 1024) {
            cfg.subscribeMaxCount = maxSubscriberCount;
        }
        if (transportMode == RtcParameterSettings.RtcSignalChannelMode.RTC_SIGNAL_CHANNEL_MODE_QUIC.ordinal()) {
            cfg.signalChannelMode = RtcParameterSettings.RtcSignalChannelMode.RTC_SIGNAL_CHANNEL_MODE_QUIC;
        }

        if ("MAINTAIN_FRAMERATE".equals(mVideoDegradationPreference)) {
            // 保帧率模式
            cfg.degradationPreference =
                    RtcParameterSettings.RtcVideoDegradationPreference.MAINTAIN_FRAMERATE;
        } else if ("MAINTAIN_RESOLUTION".equals(mVideoDegradationPreference)) {
            // 保分辨率模式
            cfg.degradationPreference =
                    RtcParameterSettings.RtcVideoDegradationPreference.MAINTAIN_RESOLUTION;
        } else if ("BALANCED".equals(mVideoDegradationPreference)) {
            // 平衡模式
            cfg.degradationPreference =
                    RtcParameterSettings.RtcVideoDegradationPreference.BALANCED;
        }
        /** 控制是否打开High Profile */
        cfg.EnableHighProfile = mEnableHighProfile;
        if (!TextUtils.isEmpty(mVideoCodec)) {
            cfg.VideoCodec = mVideoCodec;
        }

        if (cfg.VideoMaxkbps < cfg.VideoMinkbps) {
            cfg.VideoMinkbps = cfg.VideoMaxkbps;
        }
        int bitrate = JavaTypesHelper.toInt(mVideoBitrate, 0);
        if (bitrate > 0) {
            cfg.VideoMaxkbps = bitrate;
        }

        int minBitrate = JavaTypesHelper.toInt(mVideoMinBitrate, 0);
        if (minBitrate > 0) {
            // 码率
            cfg.VideoMinkbps = minBitrate;
        }


        // 是否有DataChannel数据
        cfg.HasData = mHasDataChannel;

        if (mAudioOnly) {
            // 纯音频模式
            cfg.HasVideo = false;
        }

        // 链接超时时间
        cfg.ConnectionTimeoutMs = 5000;
        // 链接读超时时间
        cfg.ReadTimeoutMs = 5000;

        if (Build.MANUFACTURER.contains("Ainemo")
                || Build.MODEL.contains("NV6001")
                || Build.MODEL.contains("NV6101")
                || Build.MODEL.contains("NV2001")
                || Build.MODEL.contains("NV5001")) {
            cfg.AudioFrequency = 16000;
            cfg.inputAudioChannel = 2;
            cfg.outputAudioChannel = 2;
            cfg.audioContentType = AudioAttributes.CONTENT_TYPE_MUSIC;
        }

        if (Build.MODEL.contains("ONEPLUS")) {
            cfg.AudioSource = MediaRecorder.AudioSource.DEFAULT;
        }

        // 是否使用多流模式，默认是true
        cfg.HasRemoteAudio = mHasRemoteAudio;
        cfg.HasRemoteVideo = mHasRemoteVideo;

        // 重连，cfg.enableAutoReconnect 如果设置true (默认是false)，则SDK自动重连，如需业务侧实现重连，则置为false
        // 若使用自动重连功能 cfg.enableListenNetwork 需为true（默认是true）
        cfg.enableAutoReconnect = mAutoReconnect;
        // 是否启用视频降级策略，极差弱网会降级到音频，保障音频通畅，默认false
        cfg.enableVideoPullDemote = mEnableVideoPullDemote;
        // 是否固定分辨率，默认false
        cfg.EnableFixedResolution = mFixResolution;

        // 自动发布
        cfg.AutoPublish = mAutoPublish;
        Log.i(TAG, "cfg.AutoPublish = " + mAutoPublish);
        // default is true.  for mVideoRoom.startPublish() set to false.
        cfg.AutoSubScribe = mAutoSubscribe;
        Log.i(TAG, "cfg.AutoSubScribe = " + mAutoSubscribe);

        // enable jitter deley can be stretched by retransmission packets
        cfg.enableJitterRetransmission = true;
        // 加密方式
        cfg.keyAgreementProto = mKeyAggrementProtocol;
        if (mKeyAggrementProtocol == RtcParameterSettings.KeyAgreementProtocol.BRTC_NONE) {
        }

        cfg.enablePruneSignal = mEnablePruneSignal;
    }

    /** 判断是否容许订阅音频 */
    public boolean isEnableSubscribeAudio() {
        if (!mEnablePruneSignal) {
            return true;
        }

        if (subscribeMode == com.baidu.rtc.model.Constants.SubscribeMode.MEETING_MODE ||
                subscribeMode == com.baidu.rtc.model.Constants.SubscribeMode.AUTO_MODE) {
            return false;
        }
        return true;
    }

    public String dumpString() {
        StringBuilder sb = new StringBuilder();
        sb.append("appId:" + mAppId + ", ");
        sb.append("token:" + mTokenStr + ", ");
        sb.append("userId:" + mUserId + ", ");
        sb.append("userName:" + mUserName + ", ");
        sb.append("roomName:" + mRoomName + ", ");
        sb.append("mediaServer:" + mMediaServer + ", ");
        sb.append("mediaServerIp:" + mMediaServerIP + ", ");
        sb.append("videoRes:" + mVideoResolution + ", ");
        sb.append("screenRes:" + mScreenResolution + ", ");
        sb.append("screenFps:" + mScreenFps + ", ");
        sb.append("rtmpUrl:" + mRtmpUrl + ", ");
        sb.append("rtmpMix:" + mRtmpMix + ", ");
        sb.append("isRecording:" + mRecording + ", ");
        sb.append("rtmpTemplate:" + mRtmpTemplate + ", ");
        sb.append("rtmpMode:" + mRtmpMode + ", ");

        sb.append("videoFps:" + mVideoFps + ", ");
        sb.append("videoBitrate:" + mVideoBitrate + ", ");
        sb.append("videoMinBitrate:" + mVideoMinBitrate + ", ");
        sb.append("videoCodec:" + mVideoCodec + ", ");
        sb.append("mVideoDegradationPreference:" + mVideoDegradationPreference + ", ");
        sb.append("mEnableHighProfile:" + mEnableHighProfile + ", ");

        sb.append("networkPolicy:" + networkPolicy + ", ");
        sb.append("keyAgreenent:" + keyAgreenent + ", ");
        sb.append("audioProfile:" + audioProfile + ", ");
        sb.append("audioScenario:" + audioScenario + ", ");

        sb.append("isBigRoomMode:" + isBigRoomMode + ", ");
        sb.append("mEnableScreenAudio:" + mEnableScreenAudio + ", ");

        sb.append("mAudioOnly:" + mAudioOnly + ", ");
        sb.append("mNoiseCancellation:" + mNoiseCancellation + ", ");
        sb.append("mEchoCancllation:" + mEchoCancllation + ", ");
        sb.append("mVocalGain:" + mVocalGain + ", ");
        sb.append("mEnableMultistream:" + mEnableMultistream + ", ");

        sb.append("mHasRemoteAudio:" + mHasRemoteAudio + ", ");
        sb.append("mHasRemoteVideo:" + mHasRemoteVideo + ", ");

        sb.append("mHasDataChannel:" + mHasDataChannel + ", ");
        sb.append("mOnlineOpen:" + mOnlineOpen + ", ");

        sb.append("mAutoSubscribe:" + mAutoSubscribe + ", ");
        sb.append("mAutoPublish:" + mAutoPublish + ", ");
        sb.append("enableBeauty:" + enableBeauty + ", ");

        sb.append("mFixResolution:" + mFixResolution + ", ");
        sb.append("subscribeMode:" + subscribeMode + ", ");
        sb.append("maxSubscriberCount:" + maxSubscriberCount +  ", ");
        sb.append("transportMode:" + transportMode + ", ");
        sb.append("mEnablePruneSignal:" + mEnablePruneSignal + ", ");
        sb.append("mAutoReconnect:" + mAutoReconnect + ", ");
        sb.append("mEnableVideoPullDemote:" + mEnableVideoPullDemote + ", ");

        sb.append("mEnableLocalCaptureAudioDump:" + mEnableLocalCaptureAudioDump + ", ");
        sb.append("mEnableMixAudioDump:" + mEnableMixAudioDump + ", ");

        sb.append("mWeakNetworkPolicy:" + mWeakNetworkPolicy + ", ");
        sb.append("mKeyAggrementProtocol:" + mKeyAggrementProtocol + ", ");
        sb.append("mAudioQuality:" + mAudioQuality + ", ");
        sb.append("mAudioScenario:" + mAudioScenario + ", ");

        return sb.toString();
    }

    static int getValueIntType(SharedPreferences prefs, String key, int def) {
        try {
            String value =  prefs.getString(key, def + "");
            if (!TextUtils.isEmpty(value)) {
                int ret = Integer.valueOf(value);
                return ret;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return def;
    }
}
