"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const path_1 = __importDefault(require("path"));
const fs_extra_1 = __importDefault(require("fs-extra"));
const ora_1 = __importDefault(require("ora"));
const getAsset_1 = __importDefault(require("../shopify/getAsset"));
const _readThemeConfig_1 = require("../utils/_readThemeConfig");
/**
 * Updates the settings_data.json config from the specified environment, if none specified
 * Then it will update from the first selected environment in config.yml usually (development).
 * @param environment - String | Boolean
 */
const updateData = ({ environment, themeid }) => __awaiter(void 0, void 0, void 0, function* () {
    const spinner = (0, ora_1.default)('Updating config/settings_data.json').start();
    if (!environment) {
        spinner.fail('No flags provided for --env or --themeid, please provide an --env to get data from.');
        return;
    }
    try {
        spinner.text = `Finding the Published Theme`;
        const env = yield (0, _readThemeConfig_1.getConfigFromEnvironment)(environment);
        const id = (themeid) ? themeid : env.theme_id;
        spinner.text = `Getting config settings from Theme: ${id}`;
        const { asset } = yield (0, getAsset_1.default)(env, id, 'config/settings_data.json');
        const { value: data } = asset;
        // Update the settings_data.json file in our shop/src/config folder from the returned result.
        fs_extra_1.default.writeFileSync(path_1.default.resolve('./shop/src/config/settings_data.json'), data.toString(), { encoding: 'utf8' });
        spinner.succeed(`Successfully updated config/settings_data.json from Theme: ${env.theme_id}`);
        return;
    }
    catch (err) {
        spinner.fail('Error updating config/settings_data.json');
        console.error(err);
        return;
    }
});
exports.default = updateData;
