'use strict'

const trending = require('node-gh-trending')
    , chalk    = require('chalk')
    , ora      = require('ora')
    , spinner  = ora('Fetching GitHub repositories...')

function splitRes (res) {
  let spl = res.split('/')

  return {
      title  : spl[1]
    , author : ' ' + spl[0]
  }
}

function handleLang (lang, name) {
  return (!lang)
  ? 'Written by' + name.author
  : 'Written in ' + lang + ' by' + name.author
}

function splitMeta (res) {
  let splt = res.split('•')
    , obj  = {}

  if (splt.length > 2) {
    obj.lang  = splt[0].trim()
    obj.stars = splt[1].trim()
  } else {
    obj.stars = splt[0].trim()
  }

  return obj
}

function contructRes (res) {
  let str = ''

  res.forEach((e, i) => {
    let name  = splitRes(e.name)
      , m     = splitMeta(e.meta)
      , title = name.title
      , link  = e.link
      , stars = m.stars.replace('stars', '⭐️ ')
      , lang  = m.lang
      , idx   = i + 1
      , desc  = e.description ? e.description + '\n' : ''

    str += idx + ')' + title + '\n' + desc + handleLang(lang, name) + '• '
    str += stars + '\n' + chalk.cyan(link)
    if (idx < 25) str += '\n'
  })

  spinner.stop()
  console.log(str)
}

const cb = (res) => { contructRes(res) }

module.exports.getRepos = function (time) {
  spinner.start()
  time ? trending.findRepos(time, cb) : trending.findRepos(cb)
}

module.exports.getReposByLang = function (lang, time) {
  spinner.start()
  time ? trending.findRepos(lang, time, cb) : trending.findRepos(lang, cb)
}

@@ -600,37 +600,36 @@
  else %7B%0A    obj.
-stars
+lang
  = splt%5B0%5D.trim(
@@ -693,16 +693,18 @@
  str = '
+%5Cn
 '%0A%0A  res
@@ -803,65 +803,25 @@
   , 
-title = name.title%0A      , link  = e.link%0A      , 
+stars = m.
 stars 
-=
+?
  m.s
@@ -848,16 +848,21 @@
 , '%E2%AD%90%EF%B8%8F ')
+ : ''
 %0A      ,
@@ -866,96 +866,110 @@
   , 
-lang  = m.lang%0A      , idx   = i + 1%0A      , desc  = e.description ? e.description + '%5Cn
+desc  = e.description ? e.description  + '%5Cn' : ''%0A      , idx   = i + 1%0A      , space = m.stars ? '%E2%80%A2 
 ' : 
@@ -992,19 +992,23 @@
 dx + ')'
- 
 + 
+name.
 title + 
@@ -1015,15 +1015,27 @@
 '%5Cn'
+%0A     
  + desc
+%0A     
  + h
@@ -1044,16 +1044,18 @@
 dleLang(
+m.
 lang, na
@@ -1064,23 +1064,15 @@
 ) + 
-'%E2%80%A2 '%0A    str
+space
  +
-=
  sta
@@ -1080,16 +1080,22 @@
 s + '%5Cn'
+%0A     
  + chalk
@@ -1099,18 +1099,29 @@
 alk.
-cyan(link)
+green(e.link) + '%5Cn'%0A
 %0A   
@@ -1203,21 +1203,19 @@
 st cb = 
-(
 res
-)
  =%3E %7B co

Handle repos without any stars