const path = require("path");
const fs = require("fs-extra");
const getPublicUrlOrPath = require("react-dev-utils/getPublicUrlOrPath");
const chalk = require("react-dev-utils/chalk");

const {
	resolveComponentsPath,
	componentsStaticPath,
	componentsStaticPathExists,
	componentsThumbnailsPath,
	componentsThumbnailsPathExists,
} = require("./griddo-config");

// Make sure any symlinks in the project folder are resolved:
// https://github.com/facebook/create-react-app/issues/637
const appDirectory = fs.realpathSync(path.resolve(__dirname, ".."));
const resolveApp = (relativePath) => path.resolve(appDirectory, relativePath);

// We use `PUBLIC_URL` environment variable or "homepage" field to infer
// "public path" at which the app is served.
// webpack needs to know it to put the right <script> hrefs into HTML even in
// single-page apps that may serve index.html for nested URLs like /todos/42.
// We can't use a relative path in HTML because we don't want to load something
// like /todos/42/static/js/bundle.7289d.js. We have to know the root.
const publicUrlOrPath = getPublicUrlOrPath(
	process.env.NODE_ENV === "development",
	require(resolveApp("package.json")).homepage,
	process.env.PUBLIC_URL,
);

const buildPath = process.env.BUILD_PATH || "exports/ax";

const moduleFileExtensions = [
	"web.mjs",
	"mjs",
	"web.js",
	"js",
	"web.ts",
	"ts",
	"web.tsx",
	"tsx",
	"json",
	"web.jsx",
	"jsx",
];

// Resolve file paths in the same order as webpack
const resolveModule = (resolveFn, filePath) => {
	const extension = moduleFileExtensions.find((extension) => fs.existsSync(resolveFn(`${filePath}.${extension}`)));

	if (extension) {
		return resolveFn(`${filePath}.${extension}`);
	}

	return resolveFn(`${filePath}.js`);
};

/* Static & Public Folder */
const appPublic = resolveApp("public");
const appHtml = resolveApp("public/index.html");
const appWebpackCache = resolveApp("node_modules/.cache");
const appStaticAssetsCache = componentsStaticPathExists ? path.resolve(appWebpackCache, "axStatic") : appPublic;

function prepareAssetsFolders() {
	if (!componentsStaticPathExists) return;

	console.log();
	console.log(chalk.yellow(`Building Static Assets cache`));
	console.log(componentsStaticPath);
	console.log(appStaticAssetsCache);
	console.log(componentsThumbnailsPath);
	console.log();

	fs.mkdirpSync(appStaticAssetsCache);

	// <components>/thumbnails folder
	if (componentsThumbnailsPathExists) {
		fs.copySync(componentsThumbnailsPath, path.resolve(appPublic, "thumbnails"), {
			dereference: true,
		});
	}

	fs.copySync(componentsStaticPath, appStaticAssetsCache, {
		dereference: true,
	});

	fs.copySync(appPublic, appStaticAssetsCache, {
		dereference: true,
		filter: (file) => file !== appHtml,
	});
}

module.exports = {
	dotenv: resolveApp(".env"),
	appPath: resolveApp("."),
	appBuild: path.resolve(process.cwd(), buildPath),
	appPublic,
	appHtml,
	appIndexJs: resolveModule(resolveApp, "src/index"),
	appPackageJson: resolveApp("package.json"),
	appSrc: resolveApp("src"),
	appTsConfig: resolveApp("tsconfig.json"),
	appJsConfig: resolveApp("jsconfig.json"),
	componentsPath: resolveComponentsPath(),
	yarnLockFile: resolveApp("yarn.lock"),
	testsSetup: resolveModule(resolveApp, "src/setupTests"),
	proxySetup: resolveApp("src/setupProxy.js"),
	appNodeModules: resolveApp("node_modules"),
	appWebpackCache,
	appTsBuildInfoFile: resolveApp("node_modules/.cache/tsconfig.tsbuildinfo"),
	swSrc: resolveModule(resolveApp, "src/service-worker"),
	publicUrlOrPath,
	componentsStaticPath,
	componentsStaticPathExists,
	appStaticAssetsCache,
	prepareAssetsFolders,
};

module.exports.moduleFileExtensions = moduleFileExtensions;
