"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());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.NetworkConnectivityValidator = void 0;
const dns = require("dns");
const yok_1 = require("../common/yok");
class NetworkConnectivityValidator {
    constructor($errors, $logger) {
        this.$errors = $errors;
        this.$logger = $logger;
    }
    validate() {
        return __awaiter(this, void 0, void 0, function* () {
            const isConnected = yield this.isConnected();
            if (!isConnected) {
                this.$errors.fail(NetworkConnectivityValidator.NO_INTERNET_ERROR_MESSAGE);
            }
        });
    }
    isConnected() {
        return new Promise((resolve, reject) => {
            dns.lookup(NetworkConnectivityValidator.DNS_LOOKUP_URL, (err) => {
                this.$logger.trace(`Error from dns.lookup is ${err}.`);
                if (err &&
                    err.code === NetworkConnectivityValidator.NO_INTERNET_ERROR_CODE) {
                    resolve(false);
                }
                else {
                    resolve(true);
                }
            });
        });
    }
}
NetworkConnectivityValidator.DNS_LOOKUP_URL = "play.nativescript.org";
NetworkConnectivityValidator.NO_INTERNET_ERROR_CODE = "ENOTFOUND";
NetworkConnectivityValidator.NO_INTERNET_ERROR_MESSAGE = "No internet connection. Check your internet settings and try again.";
exports.NetworkConnectivityValidator = NetworkConnectivityValidator;
yok_1.injector.register("networkConnectivityValidator", NetworkConnectivityValidator);
