local bindClass = luajava.bindClass
local env = _ENV

function importClass(package,customName)
  
end

importClass("androidx.appcompat.widget.LinearLayoutCompat","LinearLayout")
--...

JSON = require "mods.json"
inflate = require "mods.inflate"
LuaHttp = require "mods.luahttp"

android_R = bindClass "android.R"
R = bindClass "github.daisukiKaffuChino.reopenlua.R"
MDC_R= bindClass "com.google.android.material.R"

rippleRes = TypedValue()
activity.getTheme().resolveAttribute(android_R.attr.selectableItemBackground, rippleRes, true)
rippleResBorderless = TypedValue()
activity.getTheme().resolveAttribute(android_R.attr.selectableItemBackgroundBorderless, rippleResBorderless, true)

if activity.getSharedData("MonetDynamicColor",false) then
  DynamicColors.applyIfAvailable(this)
end

local themeUtil=LuaThemeUtil(this)
surfaceVariantColor=themeUtil.getColorSurfaceVariant()
primaryColor=themeUtil.getColorPrimary()
primaryContainerColor=themeUtil.getColorPrimaryContainer()
onPrimaryContainerColor=themeUtil.getColorOnPrimaryContainer()
secondaryColor=themeUtil.getColorSecondary()
onSurfaceColor=themeUtil.getColorOnSurface()
surfaceColor=themeUtil.getColorSurface()
outlineColor=themeUtil.getColorOutline()

OutlinedInputLayout=setmetatable({LayoutParams=TextInputLayout.LayoutParams},{
  __type=function(_)
    return "userdata"
  end,
  __call=function(_,context)
    local defStyle=MDC_R.style.Widget_MaterialComponents_TextInputLayout_OutlinedBox
    return TextInputLayout(ContextThemeWrapper(context or activity,defStyle),nil,defStyle)
    .setBoxBackgroundMode(TextInputLayout.BOX_BACKGROUND_OUTLINE)
  end,
})

OutlinedEditText=setmetatable({context=OutlinedInputLayout().context},{
  __type=function(_)
    return "userdata"
  end,
  __call=function(self)
    return TextInputEditText(self.context)
  end,
})

local LuaAsyncTask = bindClass("com.androlua.LuaAsyncTask")
local LuaThread = bindClass("com.androlua.LuaThread")
local Object = bindClass("java.lang.Object")

function thread(src, ...)

end

function task(src, ...)
  
end

function getFileDrawable(file)
  fis = FileInputStream(activity.getLuaDir().."/res/"..file..".png")
  bitmap = BitmapFactory.decodeStream(fis)
  return BitmapDrawable(activity.getResources(), bitmap)
end

function isBlank(text)
  if text==nil then
    return false
  end
  if type(text) ~= "string" then
    return true
  end
  return text:match("^%s*$") ~= nil
end

function glide(img,view)
  Glide.with(this)
  .load(activity.getLuaDir().."/res/"..img)
  .into(view)
end

function copyText(s)
  local clipboard = activity.getSystemService(Context.CLIPBOARD_SERVICE)
  local clip = ClipData.newPlainText("label", s)
  clipboard.setPrimaryClip(clip)
end

function dp2px(dp)
  return math.floor(dp*activity.resources.displayMetrics.density+0.5)
end

function initWindowStatusBar()
  EdgeToEdge.enable(this)
  if Build.VERSION.SDK_INT >= 30 then
    activity.window.setNavigationBarContrastEnforced(false)
   else
    activity.window.getDecorView().setSystemUiVisibility(
    View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION)
  end
end

function randomString()
  local random = math.random
  local chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
  local result = ""
  for i = 1, 8 do
    local index = random(1, #chars)
    result = result .. chars:sub(index, index)
  end
  return result
end

function simpleDialog(title,msg)
  MaterialAlertDialogBuilder(this)
  .setTitle(title)
  .setMessage(msg)
  .setPositiveButton("确认",nil)
  .show()
end

function getAppVersion()
  local packageInfo=activity.getApplicationContext()
  .getPackageManager().getPackageInfo(activity.getPackageName(),0)
  local verName=packageInfo.versionName
  local verCode=packageInfo.versionCode
  return verName.." ("..verCode..")"
end

function getRandomUserAgent()
  local Web_Ver = WebView.getCurrentWebViewPackage().versionName

  local release = {
    "8.0","8.1","9","10","11","12","13","14","15"
  }

  local device_model = {-- 华为p60、z50、k40、xiaomi12、13、三星Galaxy等model
    "SM-N975F","NX712J","GE2AE","V2218A","NOP-AN00","PGT-AN10",
    "V2266A","2203121C","MNA-AL00","M2012K11AC","2210132G","NOP-AN00",
    "ELS-AN00","CPH2415","CPH2583","PGZ110","LNA-AL00"
  }

  local user_agent = "Mozilla/5.0 (Linux; Android %s; %s Build/%s) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Mobile Safari/537.36"

  return string.format(
  user_agent,release[math.random(1,#release)],device_model[math.random(1,#device_model)],Build.ID,Web_Ver)
end

function openInBrowser(url)
  local success, err = pcall(function()
    local CustomTabsIntent = bindClass "androidx.browser.customtabs.CustomTabsIntent"
    local builder = CustomTabsIntent.Builder()
    builder.setToolbarColor(surfaceColor)
    builder.setShowTitle(true)
    local customTabsIntent = builder.build()

    activity.runOnUiThread(luajava.createProxy("java.lang.Runnable", {
      run = function()
        customTabsIntent.launchUrl(activity, Uri.parse(url))
      end
    }))
  end)

  if not success then
    print("启动失败: " .. tostring(err))
  end
end

function isValidEmail(email)
  if email == nil then
    return false
  end
  return PatternsCompat.EMAIL_ADDRESS.matcher(email).matches()
end

function createObservableBoolean(initialValue, callback)
  local value = initialValue

  return setmetatable({}, {
    __index = function(self, key)
      if key == "value" then
        return value
      end
    end,
    __newindex = function(self, key, newValue)
      if key == "value" and value ~= newValue then
        local oldValue = value
        value = newValue
        -- 触发回调
        if callback then
          callback(oldValue, newValue)
        end
      end
    end
  })
end

function beijingTime(utcTime)
  local utc = ZonedDateTime.parse(utcTime)
  local beijingTime = utc.withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
  return beijingTime.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME)
end

function getTimeAgo(isoTime)
  local year, month, day, hour, min, sec = string.match(isoTime, "(%d+)-(%d+)-(%d+)T(%d+):(%d+):(%d+)")
  local targetTime = os.time({
    year = tonumber(year),
    month = tonumber(month),
    day = tonumber(day),
    hour = tonumber(hour),
    min = tonumber(min),
    sec = tonumber(sec)
  })

  local currentTime = os.time()
  local diff = currentTime - targetTime
  local absDiff = math.abs(diff)
  local sign = diff >= 0 and "前" or "后"

  if absDiff < 60 then
    return string.format("刚刚")
   elseif absDiff < 3600 then
    return string.format("%d分钟%s", math.floor(absDiff / 60), sign)
   elseif absDiff < 86400 then
    return string.format("%d小时%s", math.floor(absDiff / 3600), sign)
   elseif absDiff < 2592000 then
    return string.format("%d天%s", math.floor(absDiff / 86400), sign)
   else
    return string.format("%d个月%s", math.floor(absDiff / 2592000), sign)
  end
end
