'use strict'

const prettyBytes = require('pretty-bytes')
const LegacyService = require('../legacy-service')
const { makeBadgeData: getBadgeData } = require('../../lib/badge-data')
const { makeLogo: getLogo } = require('../../lib/logos')
const {
  documentation,
  checkErrorResponse: githubCheckErrorResponse,
} = require('./github-helpers')

// This legacy service should be rewritten to use e.g. BaseJsonService.
//
// Tips for rewriting:
// https://github.com/badges/shields/blob/master/doc/rewriting-services.md
//
// Do not base new services on this code.
module.exports = class GithubSize extends LegacyService {
  static get category() {
    return 'size'
  }

  static get route() {
    return {
      base: 'github/size',
      pattern: ':user/:repo/:path*',
    }
  }

  static get examples() {
    return [
      {
        title: 'GitHub file size in bytes',
        pattern: ':user/:repo/:path',
        namedParams: {
          user: 'webcaetano',
          repo: 'craft',
          path: 'build/phaser-craft.min.js',
        },
        staticPreview: {
          label: 'size',
          message: '9.17 kB',
          color: 'green',
        },
        keywords: ['repo'],
        documentation,
      },
    ]
  }

  static registerLegacyRouteHandler({ camp, cache, githubApiProvider }) {
    camp.route(
      /^\/github\/size\/([^/]+)\/([^/]+)\/(.*)\.(svg|png|gif|jpg|json)$/,
      cache((data, match, sendBadge, request) => {
        const user = match[1] // eg, mashape
        const repo = match[2] // eg, apistatus
        const path = match[3]
        const format = match[4]
        const apiUrl = `/repos/${user}/${repo}/contents/${path}`

        const badgeData = getBadgeData('size', data)
        if (badgeData.template === 'social') {
          badgeData.logo = getLogo('github', data)
        }

        githubApiProvider.request(request, apiUrl, {}, (err, res, buffer) => {
          if (
            githubCheckErrorResponse(
              badgeData,
              err,
              res,
              'repo or file not found'
            )
          ) {
            sendBadge(format, badgeData)
            return
          }
          try {
            const body = JSON.parse(buffer)
            if (body && Number.isInteger(body.size)) {
              badgeData.text[1] = prettyBytes(body.size)
              badgeData.colorscheme = 'green'
              sendBadge(format, badgeData)
            } else {
              badgeData.text[1] = 'not a regular file'
              sendBadge(format, badgeData)
            }
          } catch (e) {
            badgeData.text[1] = 'invalid'
            sendBadge(format, badgeData)
          }
        })
      })
    )
  }
}

@@ -13,27 +13,19 @@
 %0A%0Aconst 
-prettyBytes
+Joi
  = requi
@@ -32,200 +32,174 @@
 re('
-pretty-bytes')%0Aconst LegacyService = require('../legacy-service')%0Aconst %7B makeBadgeData: getBadgeData %7D = require('../../lib/badge-data')%0Aconst %7B makeLogo: getLogo %7D = require('../../lib/logos
+joi')%0Aconst prettyBytes = require('pretty-bytes')%0Aconst %7B nonNegativeInteger %7D = require('../validators')%0Aconst %7B GithubAuthService %7D = require('./github-auth-service
 ')%0Ac
@@ -204,18 +204,16 @@
 %0Aconst %7B
-%0A 
  documen
@@ -223,57 +223,26 @@
 ion,
-%0A  checkE
+ e
 rror
-Response: githubCheckErrorResponse,%0A
+MessagesFor 
 %7D = 
@@ -273,226 +273,166 @@
 s')%0A
-%0A// This legacy service should be rewritten to use e.g. BaseJsonService.%0A//%0A// Tips for rewriting:%0A// https://github.com/badges/shields/blob/master/doc/rewriting-services.md%0A//%0A// Do not base new services on this code.
+const %7B NotFound %7D = require('..')%0A%0Aconst schema = Joi.alternatives(%0A  Joi.object(%7B%0A    size: nonNegativeInteger,%0A  %7D).required(),%0A  Joi.array().required()%0A)%0A
 %0Amod
@@ -470,22 +470,26 @@
 extends 
-Legacy
+GithubAuth
 Service 
@@ -745,46 +745,8 @@
 s',%0A
-        pattern: ':user/:repo/:path',%0A
     
@@ -902,100 +902,35 @@
 ew: 
-%7B%0A          label: 'size',%0A          message: '9.17 kB',%0A          color: 'green',%0A       
+this.render(%7B size: 9170
  %7D
+)
 ,%0A  
@@ -1013,803 +1013,279 @@
 c re
-gisterLegacyRouteHa
 nd
-l
 er(%7B 
-camp, cache, githubApiProvider %7D) %7B%0A    camp.route(%0A      /%5E%5C/github%5C/size%5C/(%5B%5E/%5D+)%5C/(%5B%5E/%5D+)%5C/(.*)%5C.(svg%7Cpng%7Cgif%7Cjpg%7Cjson)$/,%0A      cache((data, match, sendBadge, request) =%3E %7B%0A        const user = match%5B1%5D // eg, mashape%0A        const repo = match%5B2%5D // eg, apistatus%0A        const path = match%5B3%5D%0A        const format = match%5B4%5D%0A        const apiUrl = %60/repos/$%7Buser%7D/$%7Brepo%7D/contents/$%7Bpath%7D%60%0A%0A        const badgeData = getBadgeData('size', data)%0A        if (badgeData.template === 'social') %7B%0A          badgeData.logo = getLogo('github', data)%0A        %7D%0A%0A        githubApiProvider.request(request, apiUrl, %7B%7D, (err, res, buffer) =%3E %7B%0A          if (%0A            githubCheckE
+size %7D) %7B%0A    return %7B%0A      message: prettyBytes(size),%0A      color: 'blue',%0A    %7D%0A  %7D%0A%0A  async fetch(%7B user, repo, path %7D) %7B%0A    return this._requestJson(%7B%0A      url: %60/repos/$%7Buser%7D/$%7Brepo%7D/contents/$%7Bpath%7D%60,%0A      schema,%0A      errorMessages: e
 rror
-Response(%0A              badgeData,%0A              err,%0A              res,%0A              
+MessagesFor(
 'rep
@@ -1308,646 +1308,275 @@
 und'
+),
 %0A    
-        )%0A          ) %7B%0A            sendBadge(format, badgeData)%0A            return%0A          %7D%0A          try %7B%0A            const body = JSON.parse(buffer)%0A     
+%7D)%0A  %7D%0A%0A  async handle(%7B user, repo, path %7D) %7B%0A    const body = await this.fetch(%7B user, repo, path %7D)%0A
     
-   
 if (
-body && Number.isInteger(body.size)) %7B%0A              badgeData.text%5B1%5D = prettyBytes(body.size)%0A              badgeData.colorscheme = 'green'%0A              sendBadge(format, badgeData)%0A            %7D else %7B%0A              badgeData.text%5B1%5D = 'not a regular file'%0A              sendBadge(format, badgeData)%0A            %7D%0A          %7D catch (e) %7B%0A            badgeData.text%5B1%5D = 'invalid'%0A            sendBadge(format, badgeData)%0A          %7D%0A        %7D)%0A      %7D)%0A    
+Array.isArray(body)) %7B%0A      throw new NotFound(%7B prettyMessage: 'not a regular file' %7D)%0A    %7D%0A    return this.constructor.render(%7B size: body.size %7D
 )%0A  

refactor [githubsize] (#3198)