const fs = require('fs')
const path = require('path')
const https = require('https')

function downloadFile(url, filepath) {
  if (!fs.existsSync(filepath)) {
    fs.mkdirSync(path.dirname(filepath), { recursive: true })
  }

  return new Promise((resolve, reject) => {
    //忽略证书认证
    process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = 0
    try {
      https.get(
        url,
        {
          headers: {
            'User-Agent':
              'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1 Edg/102.0.5005.124'
          }
        },
        res => {
          if (res.statusCode === 200) {
            //使用数据流写入
            res.pipe(fs.createWriteStream(filepath))
            resolve()
          } else {
            res.resume()
            console.log(`Request Failed With a Status Code: ${res.statusCode}`)
            reject()
          }
        }
      )
    } catch (err) {
      console.log(err)
      reject()
    }
  })
}

module.exports.cache = async (req, res, next) => {
  const { id, x, y, z, tk, v = 'DEFAULE' } = req.params
  const host = 't0'
  const uri = `https://${host}.tianditu.gov.cn/${id}_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=${id}&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX=${z}&TILEROW=${y}&TILECOL=${x}&tk=${tk}`
  const src = path.resolve(`./data/cache/tdt/${v}/${id}/${z}/${x}/${y}.png`)

  try {
    if (!fs.existsSync(src)) {
      await downloadFile(uri, src)
    }
  } catch (_) {}

  res.sendFile(src, err => {
    if (err) return next(err)
  })
}
