"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AndroidIniFileParser = void 0;
const constants_1 = require("../../constants");
const _ = require("lodash");
const yok_1 = require("../../yok");
class AndroidIniFileParser {
    constructor($fs) {
        this.$fs = $fs;
    }
    parseIniFile(iniFilePath) {
        if (!this.$fs.exists(iniFilePath)) {
            return null;
        }
        const encoding = this.getAvdEncoding(iniFilePath);
        const contents = this.$fs.readText(iniFilePath, encoding).split("\n");
        return _.reduce(contents, (result, line) => {
            var _a, _b;
            const parsedLine = line.split("=");
            const key = (_a = parsedLine[0]) === null || _a === void 0 ? void 0 : _a.trim();
            const value = (_b = parsedLine[1]) === null || _b === void 0 ? void 0 : _b.trim();
            switch (key) {
                case "target":
                    result.target = value;
                    result.targetNum = this.readTargetNum(result.target);
                    break;
                case "path":
                case "AvdId":
                    result[_.lowerFirst(key)] = value;
                    break;
                case "hw.device.name":
                    result.device = value;
                    break;
                case "avd.ini.displayname":
                    result.displayName = value;
                    break;
                case "abi.type":
                case "skin.name":
                case "sdcard.size":
                    result[key.split(".")[0]] = value;
                    break;
            }
            return result;
        }, Object.create(null));
    }
    getAvdEncoding(avdName) {
        let encoding = "utf8";
        let contents = this.$fs.readText(avdName, "ascii");
        if (contents.length > 0) {
            contents = contents.split("\n", 1)[0];
            if (contents.length > 0) {
                const matches = contents.match(constants_1.AndroidVirtualDevice.ENCODING_MASK);
                if (matches) {
                    encoding = matches[1];
                }
            }
        }
        return encoding;
    }
    readTargetNum(target) {
        const platform = target.replace("android-", "");
        let platformNumber = +platform;
        if (isNaN(platformNumber)) {
            const googlePlatform = target.split(":")[2];
            if (googlePlatform) {
                platformNumber = +googlePlatform;
            }
            else if (platform === "L") {
                platformNumber = 20;
            }
            else if (platform === "MNC") {
                platformNumber = 22;
            }
        }
        return platformNumber;
    }
}
exports.AndroidIniFileParser = AndroidIniFileParser;
yok_1.injector.register("androidIniFileParser", AndroidIniFileParser);
