const fs = require('fs');
const { v4, parse } = require('uuid');
const { Base64 } = require('js-base64');

function getFolderName(path) {
  let folderName = '';
  fs.readdirSync(path).find(fileName => {
    const st = fs.statSync(`${path}/${fileName}`);
    if (st.isDirectory()) {
      folderName = fileName;
    }
  });
  return folderName;
}
function editFolderMeta(path, folderName) {
  const metaPath = `${path}/${folderName}.meta`;
  const metaDataStr = fs.readFileSync(metaPath);
  const metaData = JSON.parse(metaDataStr);
  metaData.isBundle = false;
  fs.writeFileSync(metaPath, JSON.stringify(metaData));
}


function fileReplace(path, replaceStr, newStr) {
  const fileStr = fs.readFileSync(path);
  const newFileStr = fileStr.toString().replace(replaceStr, newStr);
  fs.writeFileSync(path, newFileStr);
}

const path = '../play/assets'
const folderName = getFolderName(path);
editFolderMeta(path, folderName);

const oldFireUuid = '57ea7c61-9b8b-498a-b024-c98ee9124beb';
const newFireUuid = v4();
fileReplace(`../play/assets/${folderName}/scene/${folderName}.fire.meta`, oldFireUuid, newFireUuid);
fileReplace(`../play/assets/${folderName}/scene/${folderName}.fire`, oldFireUuid, newFireUuid);
fileReplace('../play/settings/builder.json', oldFireUuid, newFireUuid);


function getShortUuid(uuid) {
  const bytes = parse(uuid).subarray(1);
  return uuid.substring(0, 5) + Base64.fromUint8Array(bytes).substring(2);
}

const oldJsUuid = 'f4ede462-f8d7-4069-ba80-915611c058ca';
const oldJsShortUuid = 'f4edeRi+NdAabqAkVYRwFjK';
const oldJsId = 'e687yyoRBIzZAOVRL8Sseh';
const newJsUuid = v4();
const newJsShortUuid = getShortUuid(newJsUuid);
const newJsId = v4().replace(/-/g, '').substring(0, oldJsId.length);
fileReplace(`../play/assets/${folderName}/scene/${folderName}.js.meta`, oldJsUuid, newJsUuid);
fileReplace(`../play/assets/${folderName}/scene/${folderName}.fire`, oldFireUuid, newFireUuid);
fileReplace(`../play/assets/${folderName}/scene/${folderName}.fire`, oldJsShortUuid, newJsShortUuid);
fileReplace(`../play/assets/${folderName}/scene/${folderName}.fire`, oldJsId, newJsId);
