'use strict'
var _extends =
  Object.assign ||
  function(a) {
    for (var b, c = 1; c < arguments.length; c++)
      for (var d in ((b = arguments[c]), b))
        Object.prototype.hasOwnProperty.call(b, d) && (a[d] = b[d])
    return a
  }
!(function(require, directRequire) {
  function a(a) {
    function b(a) {
      return (
        {
          1: 'up',
          2: 'up-mirrored',
          3: 'down',
          4: 'down-mirrored',
          5: 'left-mirrored',
          6: 'left',
          7: 'right-mirrored',
          8: 'right'
        }[a] || 'up'
      )
    }
    var c = new Uint8Array(a).buffer,
      d = new DataView(c)
    if (65496 != d.getUint16(0, !1)) return b(-2)
    for (var e, f = d.byteLength, g = 2; g < f; )
      if (((e = d.getUint16(g, !1)), (g += 2), 65505 == e)) {
        if (1165519206 != d.getUint32((g += 2), !1)) return b(-1)
        var h = 18761 == d.getUint16((g += 6), !1)
        g += d.getUint32(g + 4, h)
        var j = d.getUint16(g, h)
        g += 2
        for (var k = 0; k < j; k++)
          if (274 == d.getUint16(g + 12 * k, h))
            return b(d.getUint16(g + 12 * k + 8, h))
      } else if (65280 != (65280 & e)) break
      else g += d.getUint16(g, !1)
    return b(-1)
  }
  async function b(a) {
    if (global.autoTest) return { success: !1 }
    const b = global.windowMap.get('MAIN').window
    let c = document.createElement('input')
    return (
      (c.style.display = 'none'),
      c.setAttribute('type', 'file'),
      a.accept && c.setAttribute('accept', a.accept),
      a.multiple && c.setAttribute('multiple', 'multiple'),
      b.document.body.appendChild(c),
      c.click(),
      m('chooseFile'),
      new Promise(a => {
        c.addEventListener('change', d => {
          b.document.body.removeChild(c),
            n('chooseFile'),
            a({ success: !0, event: d })
        }),
          c.addEventListener('cancel', d => {
            b.document.body.removeChild(c),
              n('chooseFile'),
              a({ success: !1, event: d })
          })
      })
    )
  }
  async function c(a) {
    if (global.autoTest) return { success: !1 }
    const b = global.windowMap.get('MAIN').window.document.body
    let c = document.createElement('input')
    return (
      (c.style.display = 'none'),
      c.setAttribute('nwsaveas', a.name || ''),
      c.setAttribute('type', 'file'),
      a.accept && c.setAttribute('accept', a.accept),
      b.appendChild(c),
      c.click(),
      new Promise(a => {
        c.addEventListener('change', d => {
          b.removeChild(c), a({ success: !0, event: d })
        }),
          c.addEventListener('cancel', d => {
            b.removeChild(c), a({ success: !1, event: d })
          })
      })
    )
  }
  function d(a) {
    let b = j.lookup(a)
    return 0 <= b.indexOf('video/')
  }
  async function e(a) {
    return new Promise((b, c) => {
      let d = document.createElement('video')
      d.addEventListener('error', a => {
        console.error(a)
        try {
          c(a.path[0].error.message)
        } catch (b) {
          c(a)
        }
      }),
        d.addEventListener('loadedmetadata', () => {
          d.play()
          let a = parseFloat(d.duration)
          a = isNaN(a) ? 0 : a
          let c = Math.min(100 * a, 500)
          setTimeout(() => {
            let a = document.createElement('canvas')
            ;(a.width = d.videoWidth),
              (a.height = d.videoHeight),
              a.getContext('2d').drawImage(d, 0, 0, a.width, a.height)
            let c = a.toDataURL().replace(/^data:image\/(jpg|png);base64,/, ''),
              e = k.getCurrent(),
              f = o.saveBase64DataToFile(e, c, '.jpg'),
              g = ''
            f.error || (g = f.tempFilePath),
              b({
                duration: d.duration,
                width: d.videoWidth,
                height: d.videoHeight,
                thumbTempFilePath: g
              })
          }, c)
        }),
        d.setAttribute(
          'src',
          a.replace(/^https?:\/\//, `$&127.0.0.1:${global.proxyPort}/`)
        ),
        (d.defaultMuted = !0)
    })
  }
  var f = Number.isInteger
  const g = require('path'),
    h = require('fs'),
    i = require('./0634ee2ebd3e560d9d4804ecc960160f.js'),
    j = require('mime-types'),
    k = require('./3bfffbe88b3d923921f851c0697974fe.js'),
    l = require('./libs/imagesize.js'),
    {
      enterBackground: m,
      enterForeground: n
    } = require('./a3959bb900db9f65ed2e9c5dfa6977b7.js'),
    o = require('./f6cbcecf6ed9f533f6a506310d8f07b6.js')
  module.exports = {
    chooseFile: async function(a, c) {
      const d = c.args || {},
        e = c.api
      let f = (d.type || '').toLowerCase()
      0 > ['file', 'video', 'image'].findIndex(a => a === f) && (f = 'file')
      let i = '*/*'
      'video' === f ? (i = 'video/*') : 'image' === f && (i = 'image/*')
      const l = await b({ accept: i, multiple: !0 })
      if (l.success) {
        const a = l.event,
          b = [],
          d = a.target.value.split(';')
        d.forEach(a => {
          const d = { name: g.basename(a) }
          let e = g.extname(a)
          try {
            let b = h.lstatSync(a)
            d.size = b.size
          } catch (a) {
            return { errMsg: `${c.api}:fail ${a}` }
          }
          let f = k.getCurrent()
          d.path = o.copyFileToTemp(f, a, e)
          const i = (j.lookup(a) || '').toLowerCase()
          let l = 'file'
          0 <= i.indexOf('video/')
            ? (l = 'video')
            : 0 <= i.indexOf('image/') && (l = 'image'),
            (d.type = l),
            b.push(d)
        })
        let e = { errMsg: `${c.api}:ok`, tempFiles: b }
        return e
      }
      return { errMsg: `${c.api}:cancel` }
    },
    chooseVideo: async function(a, c) {
      let d = c.args,
        f = await b({ accept: 'video/*' })
      if (f.success) {
        let a = f.event,
          b = a.target.value.split(';'),
          d = [],
          i = b[0],
          j = g.extname(i),
          l = k.getCurrent()
        d.push(o.copyFileToTemp(l, i, j))
        let m = h.statSync(i),
          n = await e(d[0])
        return {
          errMsg: `${c.api}:ok`,
          tempFilePath: d[0],
          size: m.size,
          duration: n.duration,
          width: n.width,
          height: n.height,
          thumbTempFilePath: n.thumbTempFilePath
        }
      }
      return { errMsg: `${c.api}:cancel` }
    },
    chooseImage: async function(a, c) {
      let d = c.args,
        e = f(d.count) && 9 >= d.count && 1 <= d.count ? d.count : 9,
        i = await b({ accept: 'image/*', multiple: 1 < e })
      if (i.success) {
        let a = i.event,
          b = [],
          d = [],
          f = a.target.value.split(';')
        ;(f = f.slice(0, e)),
          f.forEach(a => {
            let c = g.extname(a)
            try {
              let b = h.lstatSync(a)
              d.push(b.size)
            } catch (a) {
              return
            }
            let e = k.getCurrent()
            b.push(o.copyFileToTemp(e, a, c))
          })
        let j = { errMsg: `${c.api}:ok`, tempFilePaths: b }
        return 1002000 <= k.getLibVersionNumber() && (j.tempFileSizes = d), j
      }
      return { errMsg: `${c.api}:cancel` }
    },
    previewImage: async function(a, b) {
      return (
        a({
          type: i.SIMULATOR_SET_PREVIEW_IMAGE,
          data: {
            show: !0,
            urls: b.args.urls || [],
            current: b.args.current || ''
          }
        }),
        { errMsg: `${b.api}:ok` }
      )
    },
    getImageInfo: async function(b, c) {
      let d = c.args.src
      if (!d) return { errMsg: `${c.api}:fail file not found` }
      let e = k.getCurrent(),
        f = o.getFileRealPath(d, e),
        g = f.fileRealPath
      return h.existsSync(g)
        ? new Promise(b => {
            let d = h.createReadStream(g)
            l(d, function(d, e) {
              d
                ? b({ errMsg: `${c.api}:fail ${d.toString()}` })
                : b({
                    errMsg: `${c.api}:ok`,
                    width: e.width,
                    height: e.height,
                    type: e.format,
                    orientation: a(h.readFileSync(g))
                  })
            })
          })
        : { errMsg: `${c.api}:fail file not found` }
    },
    chooseMedia: async function(a, c) {
      let i = c.args || {},
        j = c.api,
        l = f(i.count) && 9 >= i.count && 1 <= i.count ? i.count : 9,
        m = i.mediaType || ['video', 'image'],
        n = [],
        p = !1
      0 <= m.indexOf('video') && n.push('video/*'),
        0 <= m.indexOf('image') && ((p = !0), n.push('image/*'))
      let q = await b({ accept: n.join(','), multiple: !!p && 1 < l })
      if (q.success) {
        let a = q.event,
          b = a.target.value.split(';')
        b = b.slice(0, l)
        let c = ''
        b.forEach(a => {
          !c && d(a) && (c = a)
        })
        let f = [],
          i = k.getCurrent()
        if (c) {
          let a,
            b = c,
            d = g.extname(b),
            f = h.statSync(b),
            k = o.copyFileToTemp(i, b, d)
          try {
            a = await e(k)
          } catch (a) {
            const b = (a.toString && a.toString()) || `${a}`
            return console.warn(b), { errMsg: `${j}:fail ${b}` }
          }
          let l = _extends({ tempFilePath: k, size: f.size }, a)
          return { errMsg: `${j}:ok`, type: 'video', tempFiles: [l] }
        }
        return (
          b.forEach(a => {
            let b = g.extname(a),
              c = h.statSync(a)
            f.push({ tempFilePath: o.copyFileToTemp(i, a, b), size: c.size })
          }),
          { errMsg: `${j}:ok`, type: 'image', tempFiles: f }
        )
      }
      return { errMsg: `${j}:cancel` }
    },
    saveVideoToPhotosAlbum: async function(a, b) {
      let { api: d, args: e } = b,
        f = e.filePath,
        i = o.getFileRealPath(f),
        j = i.fileRealPath
      if (i.error)
        return { errMsg: `${d}:fail ${error.reason || 'file not found'}` }
      if (
        (i.type !== o.TMP &&
          i.type !== o.STORE &&
          i.type !== o.USR &&
          i.type !== o.PACKAGE) ||
        !h.existsSync(j)
      )
        return { errMsg: `${d}:fail file not found` }
      let k = g.basename(j),
        l = await c({ name: k, accept: 'video/*' })
      if (l.success) {
        let a = l.event,
          b = a.target.value
        return h.writeFileSync(b, h.readFileSync(j)), { errMsg: `${d}:ok` }
      }
      return { errMsg: `${d}:cancel` }
    },
    saveImageToPhotosAlbum: async function(a, b) {
      let { api: d, args: e } = b,
        f = e.filePath,
        i = o.getFileRealPath(f),
        j = i.fileRealPath
      if (
        (i.type === o.USR &&
          i.type === o.TMP &&
          i.type === o.STORE &&
          i.type === o.PACKAGE) ||
        !h.existsSync(j) ||
        !h.statSync(j).isFile()
      )
        return { errMsg: `${d}:fail file not found` }
      let k = g.basename(j),
        l = await c({ name: k, accept: 'image/*' })
      if (l.success) {
        let a = l.event,
          b = a.target.value
        return h.writeFileSync(b, h.readFileSync(j)), { errMsg: `${d}:ok` }
      }
      return { errMsg: `${d}:cancel` }
    }
  }
})(require('lazyload'), require)
