"use strict";
/*
 * Copyright 2020 Scott Bender <scott@scottbender.net>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0

 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.listAllSerialPorts = void 0;
const fs_1 = __importDefault(require("fs"));
exports.listAllSerialPorts = () => {
    return new Promise((resolve, reject) => {
        Promise.all([
            listSafeSerialPortsDevSerialById(),
            listSafeSerialPortsDevSerialByPath(),
            listSafeSerialPortsOpenPlotter(),
            listSerialPorts()
        ])
            .then(([byId, byPath, byOpenPlotter, serialports]) => resolve({ byId, byPath, byOpenPlotter, serialports }))
            .catch(reject);
    });
};
function listSerialPorts() {
    try {
        return require('serialport').list();
    }
    catch (err) {
        return Promise.resolve([]);
    }
}
function listSafeSerialPortsDevSerialById() {
    return fs_1.default.promises
        .readdir('/dev/serial/by-id')
        .catch((err) => [])
        .then((filenames) => filenames.map((filename) => `/dev/serial/by-id/${filename}`));
}
function listSafeSerialPortsDevSerialByPath() {
    return fs_1.default.promises
        .readdir('/dev/serial/by-path')
        .catch((err) => [])
        .then((filenames) => filenames.map((filename) => `/dev/serial/by-path/${filename}`));
}
function listSafeSerialPortsOpenPlotter() {
    return fs_1.default.promises
        .readdir('/dev/')
        .catch((err) => [])
        .then((filenames) => filenames
        .filter(filename => filename.startsWith('ttyOP_'))
        .map(filename => `/dev/${filename}`));
}
