"use strict";

let _ = require("lodash");
let Q = require("q");
let fs = require("fs");
let path = require("path");
let wrench = require("wrench");
let AdmZip = require("adm-zip");

let fsCommons = require("nodebb-plugin-emoji-extended/lib/commons/fs");
let downloadCommons = require("nodebb-plugin-emoji-extended/lib/commons/download");
let index = require("./index");

const ARCHIVE = "http://emojione.com/wp-content/uploads/assets/e1-svg.zip";
const FILES_PREFIX = "https://raw.githubusercontent.com/Ranks/emojione/master/";

let updating = null;

/*===================================================== Exports  =====================================================*/

module.exports = update;

/*==================================================== Functions  ====================================================*/

function update(assetsPath) {
  if (updating == null) {
    updating = flow(assetsPath);
    updating.done(updateDone, updateDone);
  }
  return updating;
}

function flow(assetsPath) {
  return downloadSVGFiles(assetsPath)
      .then(function () { return downloadStaticFiles(assetsPath); })
      .then(function () { return index.build(assetsPath); });
}

function downloadSVGFiles(assetsPath) {
  wrench.mkdirSyncRecursive(path.resolve(assetsPath, ".."));
  return Q
      .nfcall(fsCommons.access, assetsPath, fs.F_OK)
      .then(function () { wrench.rmdirSyncRecursive(assetsPath); }, _.noop)
      .then(function () { return Q.nfcall(fs.mkdir, assetsPath); })
      .then(function () { return downloadCommons.buffer(ARCHIVE); })
      .then(function (buf) {
        let zip = new AdmZip(buf);
        zip.extractAllTo(assetsPath, true);
      });
}

function downloadStaticFiles(assetsPath) {
  return downloadCommons.buffer(FILES_PREFIX + "LICENSE.md", true)
      .then(function (buf) {
        let content = buf.toString();
        let match = /(#### Emoji One Artwork[\s\S]*)####/mi.exec(content);
        return Q.nfcall(fs.writeFile, path.join(assetsPath, "LICENSE.md"), match == null ? content : match[1].trim());
      });
}

function updateDone() { updating = null; }

@@ -1279,23 +1279,94 @@
 ;%0A  
-return Q%0A      
+let tmpPath = path.join(assetsPath, %22..%22, %22.%22 + path.basename(assetsPath));%0A  return Q
 .nfc
@@ -1387,22 +1387,19 @@
 access, 
-assets
+tmp
 Path, fs
@@ -1457,22 +1457,19 @@
 cursive(
-assets
+tmp
 Path); %7D
@@ -1482,76 +1482,8 @@
 op)%0A
-      .then(function () %7B return Q.nfcall(fs.mkdir, assetsPath); %7D)%0A
     
@@ -1640,24 +1640,349 @@
 lTo(
-assetsPath, true
+tmpPath, true);%0A        return Q%0A            .nfcall(fsCommons.access, assetsPath, fs.F_OK)%0A            .then(function () %7B wrench.rmdirSyncRecursive(assetsPath); %7D, _.noop)%0A            .then(function () %7B return Q.nfcall(fs.rename, path.join(tmpPath, %22svg%22), assetsPath); %7D)%0A            .then(function () %7B wrench.rmdirRecursive(tmpPath); %7D
 );%0A 

Revert e747f7567984ed881ecf5e510f4f599bcad2118f