package com.creyond.ecgdemo

import android.os.Bundle
import android.os.Handler
import com.creyond.sdk.JsonUtil
import com.creyond.sdk.SharedUtil
import com.google.gson.reflect.TypeToken
import kotlinx.android.synthetic.main.activity_register.*
import java.util.regex.Pattern

class RegisterActivity : BaseActivity() {
    val userList: MutableList<User> = mutableListOf()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_register)
        title = "注册"
        val str = SharedUtil.getString(this, LoginActivity.USER_LIST) ?: "[]"
        val list = JsonUtil.fromJson(str, object : TypeToken<List<User>>() {

        })
        userList.addAll(list!!)
        tv_register.setOnClickListener { register(et_name.text.toString(), et_password.text.toString()) }
    }

    internal fun register(name: String, password: String) {
        if (name.isEmpty()) {
            error("登录帐号规定为小于32位，只能为数字、字母")
            return
        }

        val pattern = Pattern.compile("^(?![0-9]+\$)(?![a-zA-Z]+\$)[0-9A-Za-z]{6,16}\$")
        if (!pattern.matcher(password).matches()) {
            error("密码规定为6-16位字母+数字")
            return
        }
        if (!userList.isEmpty()) {
            var user: User? = userList.find { name == it.name }
            if (user != null) {
                error("该帐号已存在")
                return
            }
        }

        val user = User()
        user.name = name
        user.password = password
        user.phone = et_phone.text.toString()
        if (user.phone.isNotEmpty() && user.phone.length < 11) {
            error("请输入正确的手机号")
            return
        }
        if (et_age.text.isNotEmpty()) {
            try {
                user.age = et_age.text.toString().toInt()
            } catch (e: NumberFormatException) {
                error("年龄请填写整数")
                return
            }
        }
        user.sex = et_sex.text.toString()
        if (et_height.text.isNotEmpty()) {
            try {
                user.height = et_height.text.toString().toInt()
            } catch (e: NumberFormatException) {
                error("身高请填写整数")
                return
            }
        }
        if (et_weight.text.isNotEmpty()) {
            try {
                user.weight = et_weight.text.toString().toInt()
            } catch (e: NumberFormatException) {
                error("体重请填写整数")
                return
            }
        }
        userList.add(user)
        SharedUtil.putString(this, LoginActivity.USER_LIST, JsonUtil.toJson(userList))
        success("注册成功")
        Handler().postDelayed({
            finish()
        }, 2000)
    }

}
