require "mods.func"
require "mods.api"
require "mods.userload"
local fortune=require "mods.fortune"

_response,ua=...

activity.setContentView(inflate("layout.home"))
initWindowStatusBar()
activity.getSupportActionBar().hide()

toolbar.setTitle("每日运势")
toolbar.setSubtitle(os.date("%Y年%m月%d日"))

response=JSON.decode(_response)

local function initCustomThemes(bgImageEnable,bgImageBlur)
  if bgImageEnable then
    subRoot.setBackgroundColor(surfaceColor-0x1F000000)
    if activity.getSharedData("bgImageSummary","默认")=="默认" then
      glide("Amamiya/kanban.jpg",backgroundImage,bgImageBlur)
     else
      local mGlide=Glide.with(this).load(activity.getSharedData("bgImagePath"))
      if activity.getSharedData("bgImageBlur",false) then
        mGlide.apply(RequestOptions.bitmapTransform(BlurTransformation(4, 8)))
      end
      mGlide.into(backgroundImage)
    end
    if bgImageBlur then
      subRoot.setBackgroundColor(surfaceColor-0xAF000000)
    end
   else
    subRoot.setBackgroundColor(surfaceColor)
  end
end

initCustomThemes(activity.getSharedData("bgImageEnable",true),
activity.getSharedData("bgImageBlur",false))

hitokotoContent.setShadowLayer(10,0,0,surfaceColor)
hitokotoInfo.setShadowLayer(10,0,0,surfaceColor)

bottomNav.menu.add(0,0,0,"主页")
bottomNav.menu.add(0,1,1,"排行")
bottomNav.menu.add(0,2,2,"我的")

bottomNav.menu.findItem(0).setIcon(R.drawable.ic_round_home)
bottomNav.menu.findItem(1).setIcon(R.drawable.ic_round_bar_chart)
bottomNav.menu.findItem(2).setIcon(R.drawable.ic_round_account)

local function judgeWindowSize(width,height)
  if width > height then
    bottomNav.Visibility=8
    slideNav.Visibility=0
   else
    bottomNav.Visibility=0
    slideNav.Visibility=8
  end
end

judgeWindowSize(activity.width,activity.height)

function onConfigurationChanged(configuration)
  judgeWindowSize(activity.width,activity.height)
end

slideNav.inflateMenu(R.menu.ciallo_nav_item)

slideNav.setNavigationItemSelectedListener(NavigationView.OnNavigationItemSelectedListener{
  onNavigationItemSelected=function(item)
    local itemId=item.itemId
    switch itemId do
     case R.id.nav_console
      vpg.setCurrentItem(0)
     case R.id.nav_settings
      vpg.setCurrentItem(1)
     case R.id.nav_about
      vpg.setCurrentItem(2)
    end
    return true
  end
})

local firistScrollToPageTwo = createObservableBoolean(false, function(oldValue, newValue)
  loadRanking()
end)

local firistScrollToPageThree = createObservableBoolean(false, function(oldValue, newValue)
  loadUserPage()
end)

vpg.setOnPageChangeListener(ViewPager.OnPageChangeListener{
  onPageSelected=function(v)
    bottomNav.getMenu().getItem(v).setChecked(true)
    for i=0,2 do
      slideNav.getMenu().getItem(i).setChecked(false)
    end
    slideNav.getMenu().getItem(v).setChecked(true)
    if v==1 then firistScrollToPageTwo.value=true end
    if v==2 then firistScrollToPageThree.value=true end
    if v~=0 then
      ObjectAnimator().ofFloat(fab,"scaleX",{1,0.5}).start().setDuration(200)
      ObjectAnimator().ofFloat(fab,"scaleY",{1,0.5}).start().setDuration(200)
      ObjectAnimator().ofFloat(fab,"alpha",{1,0}).start().setDuration(200)
      task(200,function()fab.setVisibility(8)end)
     else
      fab.setVisibility(0)
      ObjectAnimator().ofFloat(fab,"scaleX",{0.5,1}).start().setDuration(200)
      ObjectAnimator().ofFloat(fab,"scaleY",{0.5,1}).start().setDuration(200)
      ObjectAnimator().ofFloat(fab,"alpha",{0,1}).start().setDuration(200)
    end
end})

slideNav.getMenu().getItem(0).setChecked(true)

bottomNav.setOnNavigationItemSelectedListener(BottomNavigationView.OnNavigationItemSelectedListener{
  onNavigationItemSelected = function(item)
    vpg.setCurrentItem(item.getItemId())
    return true
end})

local addToolbarMenu=lambda a,b,c,name:toolbar.menu.add(a,b,c,name)
addToolbarMenu(0,0,0,"退出登录")
addToolbarMenu(0,1,1,"/run")
addToolbarMenu(0,2,2,"设置").setIcon(R.drawable.ic_settings).setShowAsAction(1)

toolbar.setOnMenuItemClickListener(MaterialToolbar.OnMenuItemClickListener{
  onMenuItemClick=function(item)
    local function settings()activity.newActivity("sub/settings",{response,ua})end
    switch item.getItemId() do
     case 0
      activity.setSharedData("username",nil)
      activity.setSharedData("password",nil)
      activity.newActivity("main",{true})
      activity.finishAndRemoveTask()
     case 1
      activity.finishAndRemoveTask()
     case 2
      settings()
    end
  end
})

Thread(Runnable({
  run=function()
    local _name={"anime","manga","game"}
    local name=_name[math.random(1,3)]
    local hitokotoTable=require ("mods.hitokoto."..name)

    local id=math.random(1,#hitokotoTable)

    hitokotoContent.setText(hitokotoTable[id].hitokoto)
    hitokotoInfo.setText("「"..hitokotoTable[id].from.."」")
  end
})).start()

local currentMonth = tonumber(os.date("%m"))
historyViewScroll.post(Runnable{
  run = function()
    if currentMonth>=5 and currentMonth<8 then
      local contentWidth = historyViewScroll.getChildAt(0).getWidth()
      local scrollViewWidth = historyViewScroll.getWidth()
      historyViewScroll.scrollTo((contentWidth - scrollViewWidth) / 2, 0)
     else if currentMonth>=8 then
      historyViewScroll.fullScroll(View.FOCUS_RIGHT)
    end
  end
end
})

historyView.setColorLevels({primaryColor,
  primaryColor-0x30000000,primaryColor-0x60000000,primaryColor-0x90000000,
  primaryColor-0xB0000000,primaryColor-0xC0000000,primaryColor-0xD0000000
},onSurfaceColor-0xF3000000)

local function getGreetingText(name)
  local hour = tonumber(os.date("%H"))
  local minute = tonumber(os.date("%M"))

  local greeting

  if hour >= 5 and hour < 9 then
    greeting = "喵呜~ 早上好呀 "..name.." 主人！(蹭蹭你的手) 新的一天开始啦，要一起加油哦！🌅✨"
   elseif hour >= 9 and hour < 11 then
    greeting = "喵喵~ 上午好 "..name.." 主人！(摇摇尾巴) 工作学习要顺顺利利的说，累了记得摸摸咱喵~ ☀️💕"
   elseif hour >= 11 and hour < 13 then
    if minute < 30 then
      greeting = "咕噜咕噜~ 中午到啦！(眼睛亮晶晶) "..name.." 主人该吃饭饭了喵！咱也想要小鱼干~ 🐟🍚"
     else
      greeting = "喵~ 午休时间！(蜷成一团) "..name.." 主人要和咱一起睡个甜甜的午觉吗？😴💤"
    end
   elseif hour >= 13 and hour < 17 then
    greeting = name.." 主人下午好喵~(用脑袋蹭蹭你) 下午也要元气满满喵！猫猫一直在这里陪着你~ 💪🌟"
   elseif hour >= 17 and hour < 19 then
    greeting = "呜喵~ 傍晚啦！(开心地转圈圈) "..name.." 主人辛苦了一天，快来抱抱猫猫充电吧！🌇💖"
   elseif hour >= 19 and hour < 23 then
    greeting = "喵~ 晚上好！(趴在 "..name.." 的腿上) 夜晚是最温馨的时光呢，要和咱一起度过吗？🌙✨"
   else
    greeting = "Nya... "..name.." 主人怎么还没睡呀？(担心地看着你) 熬夜对身体不好喵，咱陪你一起睡觉觉好不好喵？💤🐾"
  end

  -- 随机添加一些猫娘的小动作
  local actions = {"(用肉球轻轻拍拍你)", "(用脸颊蹭蹭你的手)", "(尾巴卷成小心心)", "(好奇地眨眨眼睛)","(用脑袋顶顶你)"}
  local randomAction = actions[math.random(#actions)]
  return greeting.."\n"..randomAction
end

local userTable=response.user
token=response.access_token
username=userTable.username
displayname=userTable.display_name
bio=userTable.bio
avatar_url=userTable.avatar_url
registration_date=userTable.registration_date
last_active_date=userTable.last_active_date
total_draws=userTable.total_draws
has_drawn_today=userTable.has_drawn_today
todays_fortune=userTable.todays_fortune
tags=userTable.tags
email=userTable.email
qq=userTable.qq
use_qq_avatar=userTable.use_qq_avatar

greetingText.setText(getGreetingText(displayname))

local function initFortuneViews(hasDrawn,fortuneData)
  if hasDrawn then
    gachaDetailCard.visibility=0
    notGachaCard.visibility=8
    fortuneTitle.text=fortuneData
    fortuneInfo.text=fortune.getIntro()[fortuneData]
    glide("Amamiya/"..fortuneData..".jpg",ammImage)
   else
    gachaDetailCard.visibility=8
    notGachaCard.visibility=0
  end
end

initFortuneViews(has_drawn_today,todays_fortune)

LuaHttp.get({
  --获取历史记录
})

fab.onClick=function()
  activity.newActivity("sub/gacha",{token,displayname})
end

function loadRanking()
  rankProgress.visibility=0
  rankErrorText.visibility=8
  rankEmptyText.visibility=8
  LuaHttp.get({
    -- api url
    API_URL().."fortune/leaderboard",
    -- headers
    getHeader({Authorization="Bearer "..token}),
    -- callback
    function(_,event)
      if pcall(JSON.decode, event) then
        local data=JSON.decode(event)
        activity.runOnUiThread(function()
          --print(event)
          if not data.detail then
            rankErrorText.visibility=8
            rankProgress.visibility=8
            if #data<1 then
              rankEmptyText.visibility=0
             else
              rankEmptyText.visibility=8
              initRankRecyclerView(data)
            end
           else
            rankErrorText.visibility=0
            rankEmptyText.visibility=8
            rankProgress.visibility=8
          end
        end)
      end
    end
  })
end

function initRankRecyclerView(t)
  local function chipView(name,uid)
    return inflate({
      Chip,
      text=name,
      alpha="0.6",
      --elevation="0.7dp",
      chipStrokeWidth="0dp",
      textColor=secondaryColor,
      --chipStrokeColor=ColorStateList.valueOf(secondaryColor-0x8F000000),
      chipBackgroundColor=ColorStateList.valueOf(secondaryColor-0xF0000000),
      chipCornerRadius="9dp",
      onClick=function()
        activity.newActivity("sub/user",{token,uid})
      end,
      onLongClick=function()
        print(uid)
        return true
      end
    })
  end
  local adp=LuaCustRecyclerAdapter(AdapterCreator({
    getItemCount=function()
      return #t
    end,
    getItemViewType=function(position)
      return 0
    end,
    onCreateViewHolder=function(parent,viewType)
      local views={}
      holder=LuaCustRecyclerHolder(inflate("layout.item_ranking",views))
      holder.view.setTag(views)
      return holder
    end,
    onBindViewHolder=function(holder,position)
      view=holder.view.getTag()
      local users=t[position+1].users
      local level=t[position+1].fortune
      view.title.text=level
      --local color=fortune.getColor()[level]-0xEF000000
      for i=1,#users do
        view.container.addView(chipView(users[i].display_name,users[i].username))
      end

    end,
  }))

  rankRV.setAdapter(adp)
  rankRV.setLayoutManager(LinearLayoutManager(this))
end


local calendar = Calendar.getInstance()
calendar.set(Calendar.HOUR_OF_DAY, 23)
calendar.set(Calendar.MINUTE, 59)
calendar.set(Calendar.SECOND, 59)
local date = calendar.getTime()

function MyTimer()
  local self = {}
  self._, self.context=xpcall(function()
    return activity.getLuaSupport()
    end,function()
    return activity or service;end)

  -- 直接用元表回收资源，不close了
  setmetatable(self, {
    __gc = function(self)
      if self.Timer then
        luajava.clear(self.Timer)
        self.Timer = nil
      end
      if self.Task then
        luajava.clear(self.Task)
        self.Task = nil
      end
      self.context.getLuaState().gc(2,1)
    end
  })

  self.init = function(func, date, ...)
    self.date = date
    self.Task = LuaTimerTask(self.context, func, Object { ... })
    self.Timer = LuaTimer(self.context, function();end, Object { ... })
  end
  self.start = function() self.Timer.schedule(self.Task, self.date) end
  self.setDate = function(date) self.date = date end
  self.getTimer = function() return self.Timer end
  self.getTask = function() return self.Task end
  return self
end

local newTimer = MyTimer()

newTimer.init(function(arg)
  arg[1].visibility=8
  arg[2].visibility=0
  --activity.setSharedData("has_drawn_today",false)
end,date,{gachaDetailCard,notGachaCard})

newTimer.start()

function onDestroy()
  newTimer=nil
end

local function updateResponseTable(intent)
  if intent.getExtra("display_name") then
    response.user.display_name=intent.getExtra("display_name")
    displayname=intent.getExtra("display_name")
    nickText.setText(displayname)
  end
  if intent.getExtra("bio") then
    response.user.bio=intent.getExtra("bio")
    bioText.text=intent.getExtra("bio")
  end
  if intent.getExtra("qq") then
    local qqnum=intent.getExtra("qq")
    response.user.qq=tonumber(qqnum)
    qq=tonumber(qqnum)
  end
  if intent.getExtra("use_qq_avatar")==true and qq then
    response.user.use_qq_avatar=intent.getExtra("use_qq_avatar")
    use_qq_avatar=intent.getExtra("use_qq_avatar")
    --print(use_qq_avatar)
    Glide.with(this).load("https://q1.qlogo.cn/g?b=qq&nk="..qq.."&s=640").into(avatar)
   else
    if not isBlank(avatar_url) then
      Glide.with(this).load(avatar_url).into(avatar)
    end
  end
end

function onActivityResult(requestCode,resultCode,intent)
  if resultCode==10 then --gacha
    local value=intent.getExtra("fortuneResult")
    initFortuneViews(true,value)
   elseif resultCode==2 then --settings monet
    local value=intent.getExtra("monet")
    if value==activity.getSharedData("MonetDynamicColor",false) then
      activity.newActivity("sub/home",android_R.anim.fade_in,android_R.anim.fade_out,{_response,ua,verinfo})
      activity.finishAndRemoveTask()
    end
   elseif resultCode==3 then --settings background
    local value=intent.getExtra("isBgConfigChanged")
    if value then
      initCustomThemes(activity.getSharedData("bgImageEnable",true),
      activity.getSharedData("bgImageBlur",false))
    end
   elseif resultCode==4 then --settings userinfo
    local value=intent.getExtra("isUserInfoChanged")
    if value then
      updateResponseTable(intent)
    end
  end
end

