"use strict";
const childProcess = require("./child-process");
const xcode = require("./xcode");
const fs = require("fs");
const path = require("path");
const _ = require("lodash");
let bplistParser = require("bplist-parser");
let plist = require("plist");
let osenv = require("osenv");
let isDeviceLogOperationStarted = false;
let pid;
let deviceLogChildProcess;
function getInstalledApplications(deviceId) {
    let rootApplicationsPath = path.join(osenv.home(), `/Library/Developer/CoreSimulator/Devices/${deviceId}/data/Containers/Bundle/Application`);
    if (!fs.existsSync(rootApplicationsPath)) {
        rootApplicationsPath = path.join(osenv.home(), `/Library/Developer/CoreSimulator/Devices/${deviceId}/data/Applications`);
    }
    let applicationGuids = fs.readdirSync(rootApplicationsPath);
    let result = [];
    _.each(applicationGuids, applicationGuid => {
        let fullApplicationPath = path.join(rootApplicationsPath, applicationGuid);
        if (fs.statSync(fullApplicationPath).isDirectory()) {
            let applicationDirContents = fs.readdirSync(fullApplicationPath);
            let applicationName = _.find(applicationDirContents, fileName => path.extname(fileName) === ".app");
            let plistFilePath = path.join(fullApplicationPath, applicationName, "Info.plist");
            result.push({
                guid: applicationGuid,
                appIdentifier: getBundleIdentifier(plistFilePath),
                path: path.join(fullApplicationPath, applicationName)
            });
        }
    });
    return result;
}
exports.getInstalledApplications = getInstalledApplications;
function startSimulator(deviceId) {
    let simulatorPath = path.resolve(xcode.getPathFromXcodeSelect(), "Applications", "Simulator.app");
    let args = ["open", simulatorPath, '--args', '-CurrentDeviceUDID', deviceId];
    childProcess.execSync(args.join(" "));
}
exports.startSimulator = startSimulator;
function getBundleIdentifier(plistFilePath) {
    let plistData;
    try {
        plistData = bplistParser.parseFileSync(plistFilePath)[0];
    }
    catch (err) {
        let content = fs.readFileSync(plistFilePath).toString();
        plistData = plist.parse(content);
    }
    return plistData && plistData.CFBundleIdentifier;
}
