/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.spark.sql.execution.ui

import scala.xml.{Node, NodeSeq}

import org.apache.spark.internal.Logging
import org.apache.spark.ui.{UIUtils, WebUIPage}

import org.apache.auron.sparkver

private[ui] class AuronAllExecutionsPage(parent: AuronSQLTab) extends WebUIPage("") with Logging {

  private val sqlStore = parent.sqlStore

  @sparkver("3.0 / 3.1 / 3.2 / 3.3 / 3.4 / 3.5")
  override def render(request: javax.servlet.http.HttpServletRequest): Seq[Node] = {
    UIUtils.headerSparkPage(request, "Auron", buildInfoSummary(sqlStore.buildInfo()), parent)
  }

  @sparkver("4.0 / 4.1")
  override def render(request: jakarta.servlet.http.HttpServletRequest): Seq[Node] = {
    UIUtils.headerSparkPage(request, "Auron", buildInfoSummary(sqlStore.buildInfo()), parent)
  }

  private def propertyHeader = Seq("Name", "Value")

  private def propertyRow(kv: (String, String)) = <tr>
    <td>
      {kv._1}
    </td> <td>
      {kv._2}
    </td>
  </tr>

  private def buildInfoSummary(buildInfoOpt: Option[AuronBuildInfoUIData]): NodeSeq = {
    buildInfoOpt match {
      case Some(buildInfo) =>
        val infos =
          UIUtils.listingTable(propertyHeader, propertyRow, buildInfo.info, fixedWidth = true)
        <div>
          <div>
            <span class="collapse-sql-properties collapse-table"
                  onClick="collapseTable('collapse-sql-properties', 'sql-properties')">
              <h4>
                <span class="collapse-table-arrow arrow-open"></span>
                <a>Auron Build Information</a>
              </h4>
            </span>
            <div class="sql-properties collapsible-table">
              {infos}
            </div>
          </div>
          <br/>
        </div>
      case None =>
        // Show a friendly empty state instead of failing or rendering a blank page.
        <div>
          <div class="alert alert-warning">
            Auron build information is not available for this application.
          </div>
        </div>
    }
  }

}
