package kr.co.itosm.dutycalendar import android.app.PendingIntent import android.content.Context import android.content.Intent import android.graphics.Typeface import android.net.Uri import android.text.SpannableString import android.text.Spanned import android.text.style.ForegroundColorSpan import android.text.style.StyleSpan import android.util.TypedValue import android.widget.RemoteViews import java.time.LocalDate import java.time.format.DateTimeFormatter import java.util.Locale /** 작은 위젯의 기본 배치는 근무 내용을 읽기 쉽게 날짜 범위를 줄인다. * 가로형은 두 주를 표시하고 세로형은 일주일의 근무 목록을 사용한다. 오늘형은 오늘과 내일에 집중한다. * 한 달 전체를 선택하면 별도의 크기 맞춤 월간 배치를 사용한다. 이곳은 기존 기본 배치를 유지한다. */ object CompactWidgetViews { private val cells=intArrayOf(R.id.compact_day_0,R.id.compact_day_1,R.id.compact_day_2,R.id.compact_day_3,R.id.compact_day_4,R.id.compact_day_5,R.id.compact_day_6, R.id.compact_day_7,R.id.compact_day_8,R.id.compact_day_9,R.id.compact_day_10,R.id.compact_day_11,R.id.compact_day_12,R.id.compact_day_13) fun start(context:Context,id:Int,kind:WidgetKind):LocalDate { val today=LocalDate.now() val base=if(kind==WidgetKind.WIDE)startOfWeek(today,ScheduleStore.load(context).weekStart) else today return base.plusDays(context.getSharedPreferences("widget",0).getInt("offset_$id",0).toLong()) } private fun dateIntent(context:Context,id:Int,date:LocalDate)=PendingIntent.getActivity(context,id, AppNavigation.date(context,date), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE) fun build(context:Context,id:Int,kind:WidgetKind,width:Int,height:Int):RemoteViews { val style=WidgetStyle.load(context,id) val schedule=ScheduleStore.load(context) val snapshot=CalendarSnapshot.load(context) val today=LocalDate.now() val density=context.resources.displayMetrics.density val layout=when(kind){WidgetKind.WIDE->R.layout.duty_widget_wide;WidgetKind.TALL->R.layout.duty_widget_tall;else->R.layout.duty_widget_today} val views=RemoteViews(context.packageName,layout) views.setInt(R.id.compact_root,"setBackgroundColor",style.background) views.setViewPadding(R.id.compact_root,(8*density).toInt(),(6*density).toInt(),(8*density).toInt(),(6*density).toInt()) views.setOnClickPendingIntent(R.id.compact_root,dateIntent(context,id,today)) views.setTextColor(R.id.compact_title,style.ink) views.setTextColor(R.id.compact_customize,style.ink) views.setTextViewTextSize(R.id.compact_title,TypedValue.COMPLEX_UNIT_SP,if(kind==WidgetKind.WIDE)14f else 12f) val customize=AppNavigation.widgetStyle(context,id) views.setOnClickPendingIntent(R.id.compact_customize,PendingIntent.getActivity(context,id,customize,PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)) if(kind==WidgetKind.TODAY) { val configured=ScheduleStore.isConfigured(context) views.setTextViewText(R.id.compact_title,today.format(DateTimeFormatter.ofPattern("M.d E",Locale.KOREAN))) views.setTextViewText(R.id.compact_shift,if(configured)schedule.shiftOn(today).title else "설정 필요") views.setTextColor(R.id.compact_shift,style.color(schedule.shiftColor(today))) val scale=style.scale/100f views.setTextViewTextSize(R.id.compact_shift,TypedValue.COMPLEX_UNIT_SP,(minOf((width-16)/5.3f,(height-64)/1.35f)).coerceIn(15f,26f)*scale) views.setInt(R.id.compact_shift,"setBackgroundColor",if(style.today)(if(style.dark)0x334A6D96 else 0x22A7B5CB) else 0) views.setTextViewText(R.id.compact_tomorrow,"내일 ${schedule.shiftOn(today.plusDays(1)).title}") views.setTextColor(R.id.compact_tomorrow,style.ink) views.setTextViewTextSize(R.id.compact_tomorrow,TypedValue.COMPLEX_UNIT_SP,11f*scale) views.setOnClickPendingIntent(R.id.compact_tomorrow,dateIntent(context,id,today.plusDays(1))) val details=detail(context,today,schedule,style,snapshot) views.setTextViewText(R.id.compact_detail,details.ifBlank{"당직근무"}) views.setTextColor(R.id.compact_detail,style.muted) views.setContentDescription(R.id.compact_shift,"${today} ${schedule.shiftOn(today).title}. $details") return views } val first=start(context,id,kind) val count=if(kind==WidgetKind.WIDE)14 else 7 val last=first.plusDays((count-1).toLong()) views.setTextViewText(R.id.compact_title,if(kind==WidgetKind.WIDE)"${first.monthValue}.${first.dayOfMonth} – ${last.monthValue}.${last.dayOfMonth}" else "${first.monthValue}월 근무") for(control in listOf(R.id.compact_previous,R.id.compact_today,R.id.compact_next))views.setTextColor(control,style.ink) listOf(R.id.compact_previous to DutyWidget.PREVIOUS,R.id.compact_today to DutyWidget.TODAY,R.id.compact_next to DutyWidget.NEXT).forEach{(control,action)-> val intent=Intent(context,kind.receiver).setAction(action).putExtra(android.appwidget.AppWidgetManager.EXTRA_APPWIDGET_ID,id) views.setOnClickPendingIntent(control,PendingIntent.getBroadcast(context,id,intent,PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)) } for(index in 0 until count) { val date=first.plusDays(index.toLong()) val shift=schedule.shiftOn(date) val holiday=Holidays.name(context,date) val events=snapshot.eventsOn(date) val anniversaries=snapshot.anniversariesOn(date) val plus=if(style.eventMark&&(events.isNotEmpty()||anniversaries.isNotEmpty()))"+" else "" val dateLabel=if(kind==WidgetKind.WIDE)date.dayOfMonth.toString()+plus else date.format(DateTimeFormatter.ofPattern("M.d E",Locale.KOREAN))+plus val shiftLabel=if(kind==WidgetKind.WIDE)shift.shortTitle else shift.title val extra=if(kind==WidgetKind.TALL&&height>=380&&style.detail!="COMPACT")detail(context,date,schedule,style,snapshot) else "" val separator=if(kind==WidgetKind.WIDE)"\n" else " " val text=dateLabel+separator+shiftLabel+(if(extra.isNotBlank())"\n$extra" else "") val styled=SpannableString(text) styled.setSpan(ForegroundColorSpan(style.color(schedule.dateColor(date,holiday!=null))),0,dateLabel.length,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) val shiftStart=dateLabel.length+separator.length styled.setSpan(ForegroundColorSpan(style.color(schedule.shiftColor(date))),shiftStart,shiftStart+shiftLabel.length,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) styled.setSpan(StyleSpan(Typeface.BOLD),shiftStart,shiftStart+shiftLabel.length,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) if(extra.isNotBlank())styled.setSpan(ForegroundColorSpan(style.muted),text.length-extra.length,text.length,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) val cell=cells[index] views.setTextViewText(cell,styled) views.setTextColor(cell,style.ink) val font=if(kind==WidgetKind.WIDE)minOf((height-54)/5.0f,(width-16)/7/3.0f).coerceIn(9f,15f) else minOf((width-16)/10f,(height-54)/7/2.4f).coerceIn(9f,14f) // 글자 확대를 선택해도 최소 높이에서 두 줄의 근무가 잘리지는 않게 상한을 둔다. // 위젯을 넓히거나 높이면 여유 공간만큼 선택한 배율이 그대로 드러난다. val lineLimit=if(kind==WidgetKind.WIDE)(height-56)/2/2.6f else (height-56)/7/2.6f views.setTextViewTextSize(cell,TypedValue.COMPLEX_UNIT_SP,minOf(font*style.scale/100,lineLimit.coerceAtLeast(8f))) views.setInt(cell,"setBackgroundColor",if(date==today&&style.today)(if(style.dark)0x554A6D96 else 0x44A7B5CB) else 0) views.setOnClickPendingIntent(cell,dateIntent(context,id,date)) views.setContentDescription(cell,"${date} ${shift.title}. ${holiday.orEmpty()} 일정 ${events.size}개. 기념일 ${anniversaries.size}개. ${detail(context,date,schedule,style,snapshot)}") } return views } private fun detail(context:Context,date:LocalDate,schedule:Schedule,style:WidgetStyle,snapshot:CalendarSnapshot):String { val values=mutableListOf() if(style.people)values.addAll(snapshot.workNames(date,schedule).map{it.name}) if(style.lunar&&schedule.showLunar)LunarDates.label(context,date)?.let{values.add(it)} if(style.holidays)Holidays.name(context,date)?.let{values.add(it)} if(style.anniversaries)snapshot.anniversariesOn(date).firstOrNull()?.let{values.add(it.getJSONObject("data").getString("title"))} if(style.people)People.onDuty(snapshot.people,date).firstOrNull()?.let{values.add(it.name)} if(style.eventMark)snapshot.eventsOn(date).size.takeIf{it>0}?.let{values.add("일정 ${it}개")} return values.joinToString(" · ") } }