package ru.yandex.atom.data

import java.net.URL
import Ordering.Implicits._

/**
 * @author avhaliullin
 */
class NormalizedUrl private(val originalHost: String, val mainMirror: String, val relUrl: String, val originalRelUrl: String) {
  def normalizedUrl: URL = new URL(mainMirror + "/" + relUrl)

  def originalUrl: URL = new URL(originalHost + "/" + originalRelUrl)

  def exportRelPart = {
    if (relUrl == originalRelUrl) {
      relUrl
    } else {
      relUrl + "\t" + originalRelUrl
    }
  }
}

object NormalizedUrl {
  private val regex = "^(.+://[^/]+)(?:/(.*))?$".r

  def cleanHost(host: String) = if (host.endsWith("/")) host.dropRight(1) else host

  def cleanRel(rel: String) = if (rel.startsWith("/")) rel.substring(1) else rel

  def apply(originalHost: String, mainMirror: String, relUrl: String, originalRelUrl: String): NormalizedUrl = {
    new NormalizedUrl(cleanHost(originalHost), cleanHost(mainMirror), cleanRel(relUrl), cleanRel(originalRelUrl))
  }

  def importFromDB(originalHost: String, mainMirror: String, relUrlsFromDB: String): NormalizedUrl = {
    val relUrls = relUrlsFromDB.split("\t", 2)
    if (relUrls.length == 1) {
      NormalizedUrl(originalHost, mainMirror, relUrlsFromDB, relUrlsFromDB)
    } else {
      NormalizedUrl(originalHost, mainMirror, relUrls(0), relUrls(1))
    }
  }

  implicit val ordering: Ordering[NormalizedUrl] = Ordering.by(x => Seq(x.mainMirror, x.relUrl))
}
