const Promise = require('bluebird')
const db = require('../../persistence')
const requests = require('./requestFactory')

const mergeUserProjects = user => {
  // any repos the user has access to that have 'literasee' as a topic
  const taggedRepos = JSON.parse(user.repos).filter(repo => repo.topics.includes('literasee'))

  // db.getProjectsByOwner() will return any repo the user has opened in the app
  // regardless of topics
  return db.getProjectsByOwner(user.username).then(projects => {
    // TODO: return thumbnail, etc.
    return projects.concat(taggedRepos).map(p => ({
      owner: typeof p.owner === 'string' ? p.owner : p.owner.login,
      name: p.name,
      description: p.description,
    }))
  })
}

module.exports = (req, res) => {
  const { username } = req.params
  const json = res.json.bind(res)

  // check for the user in the db
  db.getUser(username).then(dbUser => {
    // fetch the user's repos from GitHub if they've changed
    requests.getUserRepos(req, dbUser && dbUser.etag).then(
      // new content was available, save it to the db
      result => {
        db
          .saveUser({
            etag: result.header.etag,
            repos: JSON.stringify(result.body),
            username,
          })
          .then(mergeUserProjects)
          .then(json)
      },
      err => {
        // 304 means the user's repos haven't changed
        if (err.status === 304) {
          mergeUserProjects(dbUser).then(json)
        } else {
          // unknown error, whoops
          res.status(500).json(err)
        }
      },
    )
  })
}

@@ -316,16 +316,67 @@
 rasee'))
+%0A  const repoNames = taggedRepos.map(tr =%3E tr.name)
 %0A%0A  // d
@@ -487,16 +487,21 @@
 eturn db
+%0A    
 .getProj
@@ -522,24 +522,201 @@
 er.username)
+%0A    .then(dbProjects =%3E %7B%0A      // prevent duplicates when a project was already loaded from GitHub%0A      return dbProjects.filter(p =%3E !repoNames.includes(p.name))%0A    %7D)%0A    
 .then(projec
@@ -719,24 +719,26 @@
 ojects =%3E %7B%0A
+  
     // TODO:
@@ -761,24 +761,26 @@
 l, etc.%0A    
+  
 return proje
@@ -815,16 +815,18 @@
 p =%3E (%7B%0A
+  
       ow
@@ -885,16 +885,18 @@
 .login,%0A
+  
       na
@@ -913,16 +913,18 @@
 ,%0A      
+  
 descript
@@ -951,12 +951,16 @@
     
+  
 %7D))%0A
+  
   %7D)

Fix merging of database and GitHub projects