package lrbcol

import net.liftweb.mapper._
import net.liftweb.util._

import lrbcol.model._

import java.sql.{Connection, DriverManager, ResultSet}


object Import {
  def main(args : Array[String]) : Unit = {
      println("Here")
    DB.defineConnectionManager(DefaultConnectionIdentifier, TargetDBVendor)
    val tables = List[BaseMetaMapper](Nature, NatureLocationType,
                        Hospital, HospitalDepartment,
                        DoctorOffice, PresetLocation, EquipmentLocation,
                        Volunteer, VolunteerVolunteerGroup, VolunteerGroup,
                        Request, RequestVolunteer, RequestVolunteerGroup,
                        RequestLocation, RequestLocationIntValue, RequestLocationStringValue, RequestLocationLookupValue,
                        Client, User)
    Schemifier.destroyTables_!!(Log.infoF _, tables: _*)
    Schemifier.schemify(true, Log.infoF _, tables: _*)
//    val sourceCon = SourceDBVendor.newSuperConnection(SourceConnectionIdentifier).open_!
    DB.defineConnectionManager(SourceConnectionIdentifier, SourceDBVendor)
    
    val clients = scala.collection.mutable.Map[Long, Client]()
    val natures = scala.collection.mutable.Map[Long, Nature]()
    val nlts = scala.collection.mutable.Map[Long, NatureLocationType]()
    val vgs = scala.collection.mutable.Map[Long, VolunteerGroup]()
    val vols = scala.collection.mutable.Map[Long, Volunteer]()
    val users = scala.collection.mutable.Map[Long, User]()
    val hospitals = scala.collection.mutable.Map[Long, Hospital]()
    val departments = scala.collection.mutable.Map[Long, HospitalDepartment]()
    DB.use(SourceConnectionIdentifier) {sourceCon => 
      DB.exec(sourceCon, "select * from clients") {rs =>
        import rs._
        while(rs.next) {
          val c = Client.create.last(getString("last")).first(getString("first")).
            home(getString("home")).cell(getString("cell")).address(getString("address")).
            area(getString("area")).created(getDate("created")).modified(getDate("modified"))
          if(!c.save)
            println("Couldn't save: " + c)
          clients += getLong("id") -> c
        }
      }
      DB.exec(sourceCon, "select * from natures") {rs =>
        import rs._
        while(rs.next) {
          val (id, n) = (getLong("id"), Nature.create.name(getString("title")))
          if(!n.save)
            println("Couldn't save: " + n)
          natures += id -> n
          DB.exec(sourceCon, "select * from nature_location_types where nature_id=" + id) {rs2=>
            import rs2._
            while(rs2.next) {
              val kinds = (if(getBoolean("allow_street")) Some(LocKinds.StreetAddress.value) else None) ::
                (if(getBoolean("allow_hospital")) Some(LocKinds.Hospital.value) else None) ::
                (if(getBoolean("allow_doctor")) Some(LocKinds.DoctorOffice.value) else None) ::
                (if(getBoolean("allow_equipment")) Some(LocKinds.EquipmentLocation.value) else None) ::
                Nil flatMap{x=>x}
              val nlt = NatureLocationType.create.name(getString("name")).allowedLocationKinds.apply(kinds).nature(n)
              if(!nlt.save)
                println("Couldn't save: " + nlt)
              nlts += getLong("id") -> nlt
            }
          }
        }
      }
      DB.exec(sourceCon, "select * from volunteer_groups") {rs =>
        import rs._
        while(rs.next) {
          val vg = VolunteerGroup.create.name(getString("name")).email(getString("email"))
          if(!vg.save)
            println("Couldn't save: " + vg)
          vgs += getLong("id") -> vg
        }
      }
      DB.exec(sourceCon, "select * from volunteers") {rs =>
        import rs._
        while(rs.next) {
          val vol = Volunteer.create.code(getString("code")).last(getString("last")).first(getString("first")).email(getString("email")).sms(getBoolean("is_sms")).active(getBoolean("is_active"))
          if(!vol.save)
            println("Couldn't save: " + vol)
          vols += getLong("id") -> vol
        }
      }
      DB.exec(sourceCon, "select * from volunteer_groups_volunteers") {rs =>
        import rs._
        while(rs.next) {
          val (volId, vgId) = (getLong("volunteer_id"), getLong("volunteer_group_id"))
          val (vol, vg) = (vols(volId), vgs(vgId))
          vol.volunteerGroups += vg
          if(!vol.save)
            println("Couldn't save group " + vg + " to " + vol)
          vols += getLong("id") -> vol
        }
      }
      DB.exec(sourceCon, "select * from users") {rs =>
        import rs._
        while(rs.next) {
          val user = User.create.lastName(getString("username")).cell(getString("cell")).email(getString("email")).validated(true).password("password")
          if(!user.save)
            println("Couldn't save: " + user)
          users += getLong("id") -> user
        }
      }
      DB.exec(sourceCon, "select * from hospitals") {rs =>
        import rs._
        while(rs.next) {
          val h = Hospital.create.name(getString("name")).fullname(getString("fullname")).address(getString("address")).phone(getString("phone"))
          if(!h.save)
            println("Couldn't save: " + h)
          hospitals += getLong("id") -> h
        }
      }
      DB.exec(sourceCon, "select * from hospital_departments") {rs =>
        import rs._
        while(rs.next) {
          val dep = HospitalDepartment.create.name(getString("name"))
          if(!dep.save)
            println("Couldn't save: " + dep)
          departments += getLong("id") -> dep
        }
      }
      DB.exec(sourceCon, "select * from requests") {rs =>
        import rs._
        while(rs.next) {
          val req = Request.create.comment(getString("notes")).details(getString("notes_detailed")).created(getDate("created")).modified(getDate("modified"))
          req.priority(Priorities.cases(getInt("priority")).value)
          req.status(getString("status") match {
            case null => Statuses.Open.value
            case "COVERED" => Statuses.Covered.value
            case "RESPONDED" => Statuses.Responded.value
            case "CANCELED" => Statuses.Canceled.value
          })
          req.dispatcher(users(getLong("dispatcher_id")))
          req.client(clients(getLong("client_id")))
          req.nature(natures(getLong("nature_id")))
          if(!req.save)
            println("Couldn't save: " + req)
          val id = getLong("id")
          DB.exec(sourceCon, "select * from requests_volunteer_groups where request_id=" + id) {rs2=>
            import rs2._
            while(rs2.next) {
              if(!RequestVolunteerGroup.create.request(req).volunteerGroup(vgs(getLong("volunteer_group_id"))).timeAlerted(getDate("modified")).save)
                println("Couldn't save request/volunteer group")
            }
          }
          DB.exec(sourceCon, "select * from requests_volunteers where request_id=" + id) {rs2=>
            import rs2._
            while(rs2.next) {
              if(!RequestVolunteer.create.request(req).volunteer(vols(getLong("volunteer_id"))).save)
                println("Couldn't save request/volunteer")
            }
          }
          DB.exec(sourceCon, "select * from locations where request_id=" + id) {rs2=>
            import rs2._
            while(rs2.next) {
              val loc = RequestLocation.create
              loc.request(req)
              loc.locationType(nlts(getLong("nature_location_type_id")))
              getString("location_kind") match {
                case "STRT" =>
                  loc.locationKind(LocKinds.StreetAddress.value)
                  loc.locationValues += RequestLocationStringValue.create.field(LocKinds.Fields.StreetAddress.value).value(getString("street_address"))
                  loc.locationValues += RequestLocationStringValue.create.field(LocKinds.Fields.AddressArea.value).value(getString("street_area"))
                case "HOSP" =>
                  loc.locationKind(LocKinds.Hospital.value)
                  loc.locationValues += RequestLocationLookupValue.create.field(LocKinds.Fields.Hospital.value).value(hospitals(getLong("hospital_id")).id.is)
                  loc.locationValues += RequestLocationLookupValue.create.field(LocKinds.Fields.HospitalDepartment.value).value(departments(getLong("hospital_department_id")).id.is)
                  loc.locationValues += RequestLocationIntValue.create.field(LocKinds.Fields.HospitalRoom.value).value(getInt("room"))
                case "DCTR" =>
                  loc.locationKind(LocKinds.DoctorOffice.value)
              }
              if(!loc.save)
                println("Couldn't save: " + loc)
            }
          }
          
        }
      }
//      println("  " + clients.mkString("\n  "))
    }
  }
}
object SourceConnectionIdentifier extends ConnectionIdentifier {
  def jndiName="mysql"
}

object SourceDBVendor extends ConnectionManager {
  def releaseConnection(c: Connection) {}
  def newConnection(id: ConnectionIdentifier) = {
    Class.forName("com.mysql.jdbc.Driver")
    Full(DriverManager.getConnection("jdbc:mysql://localhost/lrbcol", "naftoli", "3701846"))
  }
  override def newSuperConnection(id: ConnectionIdentifier) = {
    newConnection(id).map(c => new SuperConnection(c, ()=>c.close, Empty))
  }
}

object TargetDBVendor extends ConnectionManager {
  
  private var pool: List[Connection] = Nil
  private var poolSize = 0
  private val maxPoolSize = 4
  

  private def createOne: Box[Connection] = try {
    val driverName: String = Props.get("db.driver") openOr
      "org.h2.Driver"

    val dbUrl: String = Props.get("db.url") openOr
      "jdbc:h2:~/lrbcol/lrbcol-prod"

    Class.forName(driverName)

    val dm = (Props.get("db.user"), Props.get("db.password")) match {
      case (Full(user), Full(pwd)) =>
        DriverManager.getConnection(dbUrl, user, pwd)
      case _ =>
        DriverManager.getConnection(dbUrl, "sa", "613613lrbcol")
    }

    Full(dm)
  } catch {
    case e: Exception => e.printStackTrace; Empty
  }

  def newConnection(name: ConnectionIdentifier): Box[Connection] =
    synchronized {
      pool match {
  case Nil if poolSize < maxPoolSize =>
    val ret = createOne
        poolSize = poolSize + 1
        ret.foreach(c => pool = c :: pool)
        ret

  case Nil => wait(1000L); newConnection(name)
  case x :: xs => try {
          x.setAutoCommit(false)
          Full(x)
        } catch {
          case e => try {
            pool = xs
            poolSize = poolSize - 1
            x.close
            newConnection(name)
          } catch {
            case e => newConnection(name)
          }
        }
      }
    }

  def releaseConnection(conn: Connection): Unit = synchronized {
    pool = conn :: pool
    notify
  }
}


