package com.sheep.gamegroup.module.login.fragments;


import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.alibaba.fastjson.JSONObject;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.LoginEntity;
import com.sheep.gamegroup.model.util.SheepSubscriber;
import com.sheep.gamegroup.module.login.controller.LoginController;
import com.sheep.gamegroup.util.DataUtil;
import com.sheep.gamegroup.util.PreferenceUtils;
import com.sheep.gamegroup.util.StringUtils;
import com.sheep.gamegroup.util.UMConfigUtils;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.base.BaseFragment;
import com.sheep.jiuyan.samllsheep.utils.G;
import com.sheep.jiuyan.samllsheep.utils.SpUtils;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * A simple {@link Fragment} subclass.
 */
public class SignUpFgt extends BaseFragment {

    private LoginController mController;

    @BindView(R.id.user_name_box)
    EditText userNameBox;
    @BindView(R.id.password_box)
    EditText passwordBox;
    @BindView(R.id.show_hide_pwd_btn)
    ImageView showHidePwdBtn;

    public SignUpFgt() {
        // Required empty public constructor
    }

    public static SignUpFgt newInstance(LoginController controller) {
        SignUpFgt fragment = new SignUpFgt();
        fragment.mController = controller;
        return fragment;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_sign_up;
    }

    @Override
    public void onViewCreated() {

    }

    @OnClick(R.id.show_hide_pwd_btn)
    public void doShowHidePwd(View v) {
        showHidePwdBtn.setSelected(!showHidePwdBtn.isSelected());
        showHidePwdBtn.setImageResource(showHidePwdBtn.isSelected() ? R.mipmap.pwd_show : R.mipmap.pwd_hide);
        if (showHidePwdBtn.isSelected()) {
            //如果选中，显示密码
            passwordBox.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        } else {
            //否则隐藏密码
            passwordBox.setTransformationMethod(PasswordTransformationMethod.getInstance());
        }
        passwordBox.setSelection(passwordBox.getText().toString().length());
    }

    @OnClick(R.id.register_btn)
    public void doRegister(View v) {
        if (!validate()) return;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("user_name", userNameBox.getText().toString().trim());
        jsonObject.put("password", passwordBox.getText().toString().trim());
        PreferenceUtils.setPrefString(SheepApp.getInstance(), UMConfigUtils.LOGIN_TYPE, UMConfigUtils.Source.SHEEP);
        SheepApp.getInstance().getNetComponent().getApiService().registerByUserName(jsonObject)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onError(BaseMessage baseMessage) {
                        hideProgress();
                        G.shortToast(baseMessage);
                    }

                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        hideProgress();
                        if (baseMessage == null) {
                            return;
                        }
                        LoginEntity loginEty = null;
                        try {
                            loginEty = JSONObject.parseObject(JSONObject.toJSONString(baseMessage.getData()), LoginEntity.class);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        if (loginEty != null) {
                            SpUtils.saveToken(getActivity(), loginEty.getToken());
                            DataUtil.getInstance().initUserEntity(loginEty.getUser());
                            mController.whenLoginSuccess(LoginController.PLATFORM_ACCOUNT, loginEty);
                        }
                    }
                });
    }

    private boolean validate() {
        String username = userNameBox.getText().toString().trim();
        String password = passwordBox.getText().toString().trim();
        if (TextUtils.isEmpty(username)) {
            G.shortToast("请输入用户名");
            return false;
        }
        if (TextUtils.isEmpty(password)) {
            G.shortToast("请输入密码");
            return false;
        }
        if (!StringUtils.isUserName(username)) {
            G.shortToast("用户名只能包含英文、数字、._-@符号，长度4-20");
            return false;
        }
        if (!StringUtils.isPassword(password)) {
            G.shortToast("密码只能包含英文、数字、_.-@$!*%符号，长度6-16");
            return false;
        }
        return true;
    }

}
