require "mods.func"
require "mods.api"

response,ua=...

local userTable=response.user
token=response.access_token
username=userTable.username
displayname=userTable.display_name
bio=userTable.bio
avatar_url=userTable.avatar_url
tags=userTable.tags
email=userTable.email
qq=userTable.qq
use_qq_avatar=userTable.use_qq_avatar

activity.setContentView(inflate("layout.settings"))
activity.getSupportActionBar().hide()
toolbar.setNavigationIcon(MDC_R.drawable.abc_ic_ab_back_material)
toolbar.setNavigationOnClickListener(function()activity.finish()end)
toolbar.setTitle("设置")
initWindowStatusBar()

tab.setupWithViewPager(vpg)
glide("ic_launcher_round.webp",icon)

if not activity.getSharedData("bgImageEnable",true) then
  --bgImageCustomLayout.visibility=8
  blurLayout.visibility=8
end

if Build.VERSION.SDK_INT >= 31 then
  monetLayout.setAlpha(1)
  monetLayout.setClickable(true)
  monetLayout.setFocusable(true)
  monetLayout.setBackgroundResource(rippleRes.resourceId)
  monetSummary.setText("已存在的 Activity 将重载")
end

local function showProgressDialog()
  return MaterialAlertDialogBuilder(this)
  .setTitle("加载中...")
  .setView(inflate({
    LinearLayout,
    layout_width="-1",
    gravity="center|start",
    {
      CircularProgressIndicator,
      indeterminate=true,
      indicatorSize=dp2px(32),
      trackCornerRadius="2dp",
      layout_margin="16dp",
    },
    {
      TextView,
      text="等待服务器回应",
    },
  }))
  .setCancelable(false)
  .create()
end

function patchRequest(dialogTitle,tv,key,isqq)

end

serverAddressLayout.onClick=function()
  local t={}
  local view=inflate("layout/dialog_edit_text",t)
  t.dialogEdt.setText(activity.getSharedData("serverAddressText","https://api.ys.oftx.top/"))
  t.dialogEdt.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_URI)
  t.dialogEdt.setHint("输入合法的地址")

  MaterialAlertDialogBuilder(this)
  .setTitle("设置请求服务器")
  .setView(view)
  .setPositiveButton("保存",function()
    local str=t.dialogEdt.text
    if not isBlank(str) then
      activity.setSharedData("serverAddressText",str)
      serverAddressText.setText(activity.getSharedData("serverAddressText"))
      --currentClient = newClient(str)
     else
      print("未能保存")
    end
  end)
  .setNeutralButton("恢复默认",function()
    activity.setSharedData("serverAddressText","")
    serverAddressText.setText(activity.getSharedData("serverAddressText"))
  end)
  .setNegativeButton("取消",nil)
  .show()
end

bgImageLayout.onClick=function()
  MaterialAlertDialogBuilder(this)
  .setTitle("设置主页背景")
  .setItems({"默认","选择图片"},function(d,i)
    if i==0 then
      print("阿喵喵可爱捏")
      activity.setSharedData("bgImageSummary","默认")
      bgImageSummary.setText("默认")
      local intent=Intent().putExtra("isBgConfigChanged",true)
      activity.setResult(3,intent)
     elseif i==1 then
      local intent = Intent(Intent.ACTION_PICK)
      intent.setType("image/*")
      activity.startActivityForResult(intent, 114514)
    end
  end)
  .setNegativeButton("取消",nil)
  .show()
end

if isBlank(bio) then
  bioText.text="未设置签名"
 else
  bioText.text=bio
end

if isBlank(avatar_url) then
  avatarText.text="未设置链接"
 else
  avatarText.text=avatar_url
end

if qq then
  qqSummary.text="已绑定："..tostring(qq)
end

nickLayout.onClick=function()
  patchRequest("设置昵称",nickText,"display_name")
end

bioLayout.onClick=function()
  patchRequest("设置签名",bioText,"bio")
end

qqLayout.onClick=function()
  if qqSummary.text=="点击绑定QQ号" then
    patchRequest("设置QQ",qqSummary,"qq",true)
   else
    print("已经绑定过啦")
  end
end

qqSwitch.setOnTouchListener{
  onTouch=function(v, event)
    if qqSummary.text=="点击绑定QQ号" then
      return
    end
    local status=v.isChecked()
    if event.getAction() == MotionEvent.ACTION_UP then
      -- 不改变状态
      local progressDialog=showProgressDialog()
      progressDialog.show()
      LuaHttp.patch({
       
      })
    end
    return true -- 消费事件，阻止后续处理
  end
}

qqSwitch.setOnCheckedChangeListener{
  onCheckedChanged=function(buttonView, isChecked)
    if qqSummary.text=="点击绑定QQ号" then
      print("先绑定，再打开")
      buttonView.setChecked(false)
      return
    end
    if isChecked then--开
      avatarLayout.visibility=8
     else--关
      avatarLayout.visibility=0
    end
    local intent=Intent()
    intent.putExtra("isUserInfoChanged",true)
    intent.putExtra("use_qq_avatar",isChecked)
    --intent.putExtra("qq",qq)
    activity.setResult(4,intent)
  end
}

avatarLayout.onClick=function()
  patchRequest("设置头像直链",avatarText,"avatar_url")
end

changePasswordLayout.onClick=function()

end

function onActivityResult(req,res,intent)
  if req==114514 then
    local BufferedInputStream=luajava.bindClass "java.io.BufferedInputStream"
    local FileOutputStream=luajava.bindClass "java.io.FileOutputStream"
    local fileName="bg_temp_"..randomString()..".png"
    local uri = intent.getData()
    local contentResolver = this.getContentResolver()
    local is = contentResolver.openInputStream(uri)
    local bis = BufferedInputStream(is, 16384)
    local bmp = BitmapFactory.decodeStream(bis)
    local file = File(activity.getExternalCacheDir(), fileName)
    local fos = FileOutputStream(file)
    local success = bmp.compress(Bitmap.CompressFormat.PNG, 100, fos)
    if success then
      activity.setSharedData("bgImageSummary","自定义")
      activity.setSharedData("bgImagePath",tostring(activity.getExternalCacheDir()).."/"..fileName)
      bgImageSummary.setText("自定义")
      local intent=Intent().putExtra("isBgConfigChanged",true)
      activity.setResult(3,intent)
     else
      print("写入图片失败")
    end
    bmp.recycle()
    bis.close()
    is.close()
    fos.close()
  end
end
