/*
   Copyright 2010 Aaron J. Radke

   Licensed 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 cc.drx

object Github{
  import Repo._
  // implicit val githubOnly = List[Repo](Repo.github) //automatic github_token specification for authentication
  case class Person(first:String, last:String)

  object Issue{
    // implicit val parser:StringMapParser[Issue] = StringMapParser.make[Issue] //from Macro
  }
  case class Issue(
    body:String,
    number:Int,
    state:String,
    title:String,
    // labels:Seq[String], //hide seq
    // assignees:Seq[String],
    // milestone:String,
    comments:Int,
    updated_at:Date
  ) //TODO add more fields

  private val githubSource = new SourceGithub(OS.Env.get("GITHUB_TOKEN"))
  private val githubRepo = new Repo(githubSource, None, Repo.GithubStyle)
  private implicit val repos:Repo.Repos = Iterable(githubRepo)

  //--helper
  def projects(orgName:String):Future[List[Project]] = githubSource.projectsF(Org(orgName))

  def issues(orgName:String, prjName:String) = githubSource.issuesF(Org(orgName) / prjName)

  def clone(org:String, prj:String, parentDir:File)(implicit ec:ExecutionContext):Future[Git] = clone(Org(org)/prj, parentDir)
  def clone(prj:Project, parentDir:File)(implicit ec:ExecutionContext):Future[Git] = {
    val workingDir = (parentDir/prj.name).canon
    val cloneUrl = s"git@github.com:${prj.org.name}/${prj.name}.git"
    println(s"Clone from: $cloneUrl\n       to:$workingDir")
    Shell("git","clone",  cloneUrl, workingDir.path).run.map{res =>
      Git(workingDir/".git")
    }
  }

  def clone(org:String, parentDir:File)(implicit ec:ExecutionContext):Future[List[Git]] = clone(Org(org), parentDir)
  def clone(org:Org, parentDir:File)(implicit ec:ExecutionContext):Future[List[Git]] = {

    val remoteGitProjects:Future[List[Git]] = Future.traverse(org.list(repos)){prj => //TODO use a non-blocking org.list lookup
      val workingDir = (parentDir/prj.name).canon

      //--fetch/pull if it already exists
      val res = {
        if(workingDir.isDir){
          val git = Git(workingDir/".git")

          git.fetch().map{lines =>
            git.isDirty.foreach{dirty =>
              if(!dirty) git.merge().foreach{_ => println(s"Pulled:  $workingDir" ansi Green)} //Fetch + merge = pull
              else {
                val branch = git.branch blockWithoutWarning 10.s getOrElse "HEAD" //TODO make a non blocking lookup
                println(s"Fetched: $workingDir ($branch)" ansi Red)  //Fetch (without merge)
              }
            }
            git //return the git
          }
        }
        //--clone if you don't have it yet
        else          { println(s"Cloning:  $workingDir" ansi Blue); Github.clone(prj, parentDir) }
      }
      res.onComplete{
        case Failure(e) => println(s"Error: $workingDir ($e)" ansi Red)
        case _ =>
      }
      res
    }

    remoteGitProjects.map{ gits =>

      val remoteNames = gits.map{_.dir.name}.toSet
      val ignoreNames = Set("archive","tmp")
      val localNames = parentDir.list.filter(_.isDir).map{_.name}.filter(_ != "archive" /*FIXME or is remote url*/).toSet
      val remoteWikiNames = remoteNames.map{_ + ".wiki"}
      val namesToArchive = localNames -- remoteNames -- remoteWikiNames -- ignoreNames

      //archive old files
      (parentDir/"archive").mkDir.map{archiveDir =>
        namesToArchive foreach {name =>
          val dir = parentDir/name
          println(s"need to archive: $dir" ansi Yellow) //TODO remove this debug
          // TODO add Check if is git directory and can pull from Github
          if((archiveDir/"name").isDir) println(s"Warning archive already exists: $dir" ansi Red)
          else { println(s"Archiving: $dir" ansi Orange);  dir moveTo archiveDir }
        }
      }
      gits //return the git projects that were pulled down
    }
  }

  def main(args:Array[String]):Unit = {
    import Implicit.ec
    args match {
      case Array("clone-org", org, localDir) => clone(Org(org), File(localDir).canon).blockWithoutWarning(1.hr)
    }
    ()
  }

}