import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { usePushForm } from './usePushForm'
import { usePushServers } from './usePushServers'
import { usePushProgress } from './usePushProgress'
import { usePushPreview } from './usePushPreview'
import { usePushLogs } from './usePushLogs'

/** Orchestrates push page composables and lifecycle */
export function usePushPage() {
  const form = usePushForm()
  const pushStatus = ref<Record<number, string>>({})
  const servers = usePushServers(pushStatus)
  const logs = usePushLogs(form, servers)
  const progress = usePushProgress(form, servers, () => logs.loadLogs())
  const preview = usePushPreview(form, servers)

  function onConfirmAndPush() {
    preview.confirmAndPush(() => progress.doPush())
  }

  onMounted(() => {
    servers.loadServers()
    logs.loadLogs()
    servers.startAutoRefresh(() => progress.pushing.value)
  })

  onUnmounted(() => {
    progress.dispose()
    servers.stopAutoRefresh()
  })

  return {
    form: reactive(form),
    servers: reactive(servers),
    progress: reactive(progress),
    preview: reactive(preview),
    logs: reactive(logs),
    onConfirmAndPush,
  }
}
