// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.

import {FileSystem} from "../common/node/fileSystem";
import * as path from "path";
import * as vscode from "vscode";
import {CommandPaletteHandler} from "./commandPaletteHandler";
import {ReactNativeProjectHelper} from "../common/reactNativeProjectHelper";
import {ReactDirManager} from "./reactDirManager";
import {IntellisenseHelper} from "./IntellisenseHelper";
import {TelemetryHelper} from "../common/TelemetryHelper";
import {EntryPoint} from "../common/entryPoint";

const outputChannel = vscode.window.createOutputChannel("React-Native");
const entryPoint = new EntryPoint(outputChannel);
const commandPaletteHandler = new CommandPaletteHandler(vscode.workspace.rootPath);
const reactNativeProjectHelper = new ReactNativeProjectHelper(vscode.workspace.rootPath);
const fsUtil = new FileSystem();

export function activate(context: vscode.ExtensionContext): void {
    entryPoint.runApp("react-native", () => <string>require("../../package.json").version, "Failed to activate the React Native Tools extension", () => {
        return reactNativeProjectHelper.isReactNativeProject()
            .then(isRNProject => {
                if (isRNProject) {
                    warnWhenReactNativeVersionIsNotSupported();
                    entryPoint.runCode("debugger.setupLauncherStub", "Failed to setup the stub launcher for the debugger", () =>
                        setupReactNativeDebugger().then(() =>
                            setupReactDir(context)), /*areErrorsFatal*/ false);
                    entryPoint.runCode("intelliSense.setup", "Failed to setup IntelliSense", () =>
                        IntellisenseHelper.setupReactNativeIntellisense(), /*areErrorsFatal*/ false);
                }
                entryPoint.runCode("debugger.setupNodeDebuggerLocation", "Failed to configure the node debugger location for the debugger", () =>
                    configureNodeDebuggerLocation(), /*areErrorsFatal*/ false);
                registerReactNativeCommands(context);
            });
    });
}

export function deactivate(): void {
    // Kill any packager processes that we spawned
    entryPoint.runCode("extension.deactivate", "Failed to stop the packager while closing React Native Tools",
        () => commandPaletteHandler.stopPackager(), /*areErrorsFatal*/ true);
}

function configureNodeDebuggerLocation(): Q.Promise<void> {
    const nodeDebugPath = vscode.extensions.getExtension("andreweinand.node-debug").extensionPath;
    return fsUtil.writeFile(path.resolve(__dirname, "../", "debugger", "nodeDebugLocation.json"), JSON.stringify({ nodeDebugPath }));
}

function setupReactDir(context: vscode.ExtensionContext): Q.Promise<void> {
    const reactDirManager = new ReactDirManager();
    let createdDir = reactDirManager.create();
    context.subscriptions.push(reactDirManager);
    return createdDir;
}

function warnWhenReactNativeVersionIsNotSupported(): void {
    return reactNativeProjectHelper.validateReactNativeVersion().done(() => { }, reason => {
        TelemetryHelper.sendSimpleEvent("launchDebuggerError", { rnVersion: reason });
        const shortMessage = `React Native Tools only supports React Native versions 0.19.0 and later`;
        const longMessage = `${shortMessage}: ${reason}`;
        vscode.window.showWarningMessage(shortMessage);
        outputChannel.appendLine(longMessage);
        outputChannel.show();
    });
}

function registerReactNativeCommands(context: vscode.ExtensionContext): void {
    // Register React Native commands
    registerVSCodeCommand(context, "runAndroid", "Failed to run the application in Android", () => commandPaletteHandler.runAndroid());
    registerVSCodeCommand(context, "runIos", "Failed to run the application in iOS", () => commandPaletteHandler.runIos());
    registerVSCodeCommand(context, "startPackager", "Failed to start the React Native packager", () => commandPaletteHandler.startPackager());
    registerVSCodeCommand(context, "stopPackager", "Failed to stop the React Native packager", () => commandPaletteHandler.stopPackager());
}

function registerVSCodeCommand(
    context: vscode.ExtensionContext, commandName: string,
    errorDescription: string, commandHandler: () => Q.Promise<void>): void {
    context.subscriptions.push(vscode.commands.registerCommand(
        `reactNative.${commandName}`,
        () =>
            entryPoint.runCode(
                `commandPalette.${commandName}`, errorDescription,
                commandHandler, /*areErrorsFatal*/ false)));
}

/**
 * Sets up the debugger for the React Native project by dropping
 * the debugger stub into the workspace
 */
function setupReactNativeDebugger(): Q.Promise<void> {
    const launcherPath = require.resolve("../debugger/launcher");
    const pkg = require("../../package.json");
    const extensionVersionNumber = pkg.version;
    const extensionName = pkg.name;

    let debuggerEntryCode =
        `// This file is automatically generated by ${extensionName}@${extensionVersionNumber}
// Please do not modify it manually. All changes will be lost.
try {
    var path = require("path");
    var Launcher = require(${JSON.stringify(launcherPath)}).Launcher;
    new Launcher(path.resolve(__dirname, "..")).launch();
} catch (e) {
    throw new Error("Unable to launch application. Try deleting .vscode/launchReactNative.js and restarting vscode.");
}`;

    const vscodeFolder = path.join(vscode.workspace.rootPath, ".vscode");
    const debugStub = path.join(vscodeFolder, "launchReactNative.js");

    return fsUtil.ensureDirectory(vscodeFolder)
        .then(() => fsUtil.ensureFileWithContents(debugStub, debuggerEntryCode))
        .catch((err: Error) => {
            vscode.window.showErrorMessage(err.message);
        });
}
