"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.WebViewChannelRendererSide = exports.InProcessChannel = exports.ReadyState = void 0;

var _debug = _interopRequireDefault(require("debug"));

var _events = require("events");

var _server = require("./server");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/*
 * Copyright 2019 IBM Corporation
 *
 * 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 __awaiter = void 0 && (void 0).__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());
  });
};
/* eslint-disable @typescript-eslint/explicit-member-accessibility */


const debug = (0, _debug.default)('plugins/bash-like/pty/channel');
var ReadyState;
exports.ReadyState = ReadyState;

(function (ReadyState) {
  ReadyState[ReadyState["CONNECTING"] = 0] = "CONNECTING";
  ReadyState[ReadyState["OPEN"] = 1] = "OPEN";
  ReadyState[ReadyState["CLOSING"] = 2] = "CLOSING";
  ReadyState[ReadyState["CLOSED"] = 3] = "CLOSED";
})(ReadyState || (exports.ReadyState = ReadyState = {}));
/**
 * Channel impl for direct, in-electron communication
 *
 */


class InProcessChannel extends _events.EventEmitter {
  constructor(otherSide) {
    super();
    this.readyState = ReadyState.OPEN;

    if (otherSide) {
      this.otherSide = otherSide;
    } else {
      this.otherSide = new InProcessChannel(this);
    }
  }

  init() {
    return __awaiter(this, void 0, void 0, function* () {
      debug('IPC init');
      yield (0, _server.onConnection)(yield (0, _server.disableBashSessions)())(this.otherSide); // emit 'open' on our side

      this.emit('open');
      debug('IPC init done');
    });
  }
  /** Forcibly close the channel */


  close() {// no-op
  }
  /** emit 'message' on the other side */


  send(msg) {
    if (this.otherSide.readyState === ReadyState.OPEN) {
      try {
        this.otherSide.emit('message', msg);
      } catch (err) {
        console.error(err);
      }
    }
  } // eslint-disable-next-line @typescript-eslint/no-explicit-any


  removeEventListener(eventType, handler) {
    this.off(eventType, handler);
  }

}
/**
 * Thin wrapper on top of WebView postMessage
 *
 */


exports.InProcessChannel = InProcessChannel;

class WebViewChannelRendererSide extends _events.EventEmitter {
  constructor() {
    super(...arguments);
    this.readyState = ReadyState.OPEN;
  }

  init() {
    return __awaiter(this, void 0, void 0, function* () {
      debug('IPC init');
      const {
        body
      } = yield window['webview-proxy']({
        command: 'init',
        provider: 'pty',
        channel: this
      });
      this.channelId = body.channelId;
      console.log(`CHANNELID ${this.channelId}`); // emit 'open' on our side

      this.emit('open');
      debug('IPC init done');
    });
  }
  /** Forcibly close the channel */


  close() {
    this.emit('exit');
  }
  /** emit 'message' on the other side */


  send(body) {
    console.log(`SEND ${this.channelId}`);
    window['webview-proxy']({
      command: 'send',
      provider: 'pty',
      channelId: this.channelId,
      body
    });
  } // eslint-disable-next-line @typescript-eslint/no-explicit-any


  removeEventListener(eventType, handler) {
    this.off(eventType, handler);
  }

}

exports.WebViewChannelRendererSide = WebViewChannelRendererSide;