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());
  });
};
var __generator = (this && this.__generator) || function(thisArg, body) {
  var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] },
    f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
  return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;

  function verb(n) { return function(v) { return step([n, v]); }; }

  function step(op) {
    if (f) throw new TypeError("Generator is already executing.");
    while (g && (g = 0, op[0] && (_ = 0)), _) try {
      if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
      if (y = 0, t) op = [op[0] & 2, t.value];
      switch (op[0]) {
        case 0:
        case 1:
          t = op;
          break;
        case 4:
          _.label++;
          return { value: op[1], done: false };
        case 5:
          _.label++;
          y = op[1];
          op = [0];
          continue;
        case 7:
          op = _.ops.pop();
          _.trys.pop();
          continue;
        default:
          if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
          if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
          if (op[0] === 6 && _.label < t[1]) {
            _.label = t[1];
            t = op;
            break;
          }
          if (t && _.label < t[2]) {
            _.label = t[2];
            _.ops.push(op);
            break;
          }
          if (t[2]) _.ops.pop();
          _.trys.pop();
          continue;
      }
      op = body.call(thisArg, _);
    } catch (e) {
      op = [6, e];
      y = 0;
    } finally { f = t = 0; }
    if (op[0] & 5) throw op[1];
    return { value: op[0] ? op[1] : void 0, done: true };
  }
};

/* eslint-disable */
var ChiptuneAudioContext = window.AudioContext || window.webkitAudioContext;
var libopenmpt;
var libopenmptLoadPromise;

class ChiptuneJsConfig {
  constructor(repeatCount, context) {
    this.repeatCount = repeatCount;
    this.context = context;
  }
};

class ChiptuneJsPlayer {
  constructor(config) {
    this.config = config;
    this.audioContext = config.context || new ChiptuneAudioContext();
    this.context = this.audioContext.createGain();
    this.currentPlayingNode = null;
    this.handlers = [];
    this.touchLocked = true;
    this.volume = 1;
  }
  initialize() {
    var _this = this;
    if (libopenmptLoadPromise)
      return libopenmptLoadPromise;
    if (libopenmpt)
      return Promise.resolve();
    libopenmptLoadPromise = new Promise(function(resolve, reject) {
      return __awaiter(_this, void 0, void 0, function() {
        var Module_1, e_1;
        return __generator(this, function(_a) {
          switch (_a.label) {
            case 0:
              _a.trys.push([0, 3, 4, 5]);
              return [4 /*yield*/ , Promise.resolve().then(function() { return require('./libopenmpt/libopenmpt.js'); })];
            case 1:
              Module_1 = (_a.sent()).Module;
              return [4 /*yield*/ , new Promise(function(resolve) {
                Module_1['onRuntimeInitialized'] = resolve;
              })];
            case 2:
              _a.sent();
              libopenmpt = Module_1;
              resolve();
              return [3 /*break*/ , 5];
            case 3:
              e_1 = _a.sent();
              reject(e_1);
              return [3 /*break*/ , 5];
            case 4:
              libopenmptLoadPromise = undefined;
              return [7 /*endfinally*/ ];
            case 5:
              return [2 /*return*/ ];
          }
        });
      });
    });
    return libopenmptLoadPromise;
  }
  fireEvent(eventName, response) {
    var handlers = this.handlers;
    if (handlers.length > 0) {
      for (var _i = 0, handlers_1 = handlers; _i < handlers_1.length; _i++) {
        var handler = handlers_1[_i];
        if (handler.eventName === eventName) {
          handler.handler(response);
        }
      }
    }
  }
  addHandler(eventName, handler) {
    this.handlers.push({ eventName: eventName, handler: handler });
  }
  onEnded(handler) {
    this.addHandler('onEnded', handler);
  }
  onError(handler) {
    this.addHandler('onError', handler);
  }
  duration() {
    return libopenmpt._openmpt_module_get_duration_seconds(this.currentPlayingNode.modulePtr);
  }
  position() {
    return libopenmpt._openmpt_module_get_position_seconds(this.currentPlayingNode.modulePtr);
  }
  seek(position) {
    if (this.currentPlayingNode) {
      libopenmpt._openmpt_module_set_position_seconds(this.currentPlayingNode.modulePtr, position);
    }
  }
  metadata() {
    var data = {};
    var keys = libopenmpt.UTF8ToString(libopenmpt._openmpt_module_get_metadata_keys(this.currentPlayingNode.modulePtr)).split(';');
    var keyNameBuffer = 0;
    for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) {
      var key = keys_1[_i];
      keyNameBuffer = libopenmpt._malloc(key.length + 1);
      libopenmpt.writeAsciiToMemory(key, keyNameBuffer);
      data[key] = libopenmpt.UTF8ToString(libopenmpt._openmpt_module_get_metadata(this.currentPlayingNode.modulePtr, keyNameBuffer));
      libopenmpt._free(keyNameBuffer);
    }
    return data;
  }
  unlock() {
    var context = this.audioContext;
    var buffer = context.createBuffer(1, 1, 22050);
    var unlockSource = context.createBufferSource();
    unlockSource.buffer = buffer;
    unlockSource.connect(this.context);
    this.context.connect(context.destination);
    unlockSource.start(0);
    this.touchLocked = false;
  }
  load(input) {
    var _this = this;
    return this.initialize().then(function() {
      return new Promise(function(resolve, reject) {
        if (_this.touchLocked) {
          _this.unlock();
        }
        var player = _this;
        if (input instanceof File) {
          var reader_1 = new FileReader();
          reader_1.onload = function() {
            resolve(reader_1.result);
          };
          reader_1.readAsArrayBuffer(input);
        } else {
          window.fetch(input).then(function(response) {
            response.arrayBuffer().then(function(arrayBuffer) {
              resolve(arrayBuffer);
            }).catch(function(error) {
              reject(error);
            });
          }).catch(function(error) {
            reject(error);
          });
        }
      });
    });
  }
  play(buffer) {
    this.unlock();
    this.stop();
    var processNode = this.createLibopenmptNode(buffer, this.buffer);
    if (processNode === null) {
      return;
    }
    libopenmpt._openmpt_module_set_repeat_count(processNode.modulePtr, this.config.repeatCount || 0);
    this.currentPlayingNode = processNode;
    processNode.connect(this.context);
    this.context.connect(this.audioContext.destination);
  }
  stop() {
    if (this.currentPlayingNode != null) {
      this.currentPlayingNode.disconnect();
      this.currentPlayingNode.cleanup();
      this.currentPlayingNode = null;
    }
  }
  togglePause() {
    if (this.currentPlayingNode != null) {
      this.currentPlayingNode.togglePause();
    }
  }
  getPattern() {
    if (this.currentPlayingNode && this.currentPlayingNode.modulePtr) {
      return libopenmpt._openmpt_module_get_current_pattern(this.currentPlayingNode.modulePtr);
    }
    return 0;
  }
  getRow() {
    if (this.currentPlayingNode && this.currentPlayingNode.modulePtr) {
      return libopenmpt._openmpt_module_get_current_row(this.currentPlayingNode.modulePtr);
    }
    return 0;
  }
  getNumPatterns() {
    if (this.currentPlayingNode && this.currentPlayingNode.modulePtr) {
      return libopenmpt._openmpt_module_get_num_patterns(this.currentPlayingNode.modulePtr);
    }
    return 0;
  }
  getCurrentSpeed() {
    if (this.currentPlayingNode && this.currentPlayingNode.modulePtr) {
      return libopenmpt._openmpt_module_get_current_speed(this.currentPlayingNode.modulePtr);
    }
    return 0;
  }
  getCurrentTempo() {
    if (this.currentPlayingNode && this.currentPlayingNode.modulePtr) {
      return libopenmpt._openmpt_module_get_current_tempo(this.currentPlayingNode.modulePtr);
    }
    return 0;
  }
  getPatternNumRows(pattern) {
    if (this.currentPlayingNode && this.currentPlayingNode.modulePtr) {
      return libopenmpt._openmpt_module_get_pattern_num_rows(this.currentPlayingNode.modulePtr, pattern);
    }
    return 0;
  }
  getPatternRowChannel(pattern, row, channel) {
    if (this.currentPlayingNode && this.currentPlayingNode.modulePtr) {
      return libopenmpt.UTF8ToString(libopenmpt._openmpt_module_format_pattern_row_channel(this.currentPlayingNode.modulePtr, pattern, row, channel, 0, true));
    }
    return '';
  }
  getCtls() {
    if (this.currentPlayingNode && this.currentPlayingNode.modulePtr) {
      return libopenmpt._openmpt_module_get_ctls(this.currentPlayingNode.modulePtr);
    }
    return 0;
  }
  version() {
    if (this.currentPlayingNode && this.currentPlayingNode.modulePtr) {
      return libopenmpt._openmpt_get_library_version();
    }
    return 0;
  }
  createLibopenmptNode(buffer, config) {
    var maxFramesPerChunk = 4096;
    var processNode = this.audioContext.createScriptProcessor(2048, 0, 2);
    processNode.config = config;
    processNode.player = this;
    var byteArray = new Int8Array(buffer);
    var ptrToFile = libopenmpt._malloc(byteArray.byteLength);
    libopenmpt.HEAPU8.set(byteArray, ptrToFile);
    processNode.modulePtr = libopenmpt._openmpt_module_create_from_memory(ptrToFile, byteArray.byteLength, 0, 0, 0);
    processNode.nbChannels = libopenmpt._openmpt_module_get_num_channels(processNode.modulePtr);
    processNode.patternIndex = -1;
    processNode.paused = false;
    processNode.leftBufferPtr = libopenmpt._malloc(4 * maxFramesPerChunk);
    processNode.rightBufferPtr = libopenmpt._malloc(4 * maxFramesPerChunk);
    processNode.perf = { 'current': 0, 'max': 0 };
    processNode.cleanup = function() {
      if (this.modulePtr !== 0) {
        libopenmpt._openmpt_module_destroy(this.modulePtr);
        this.modulePtr = 0;
      }
      if (this.leftBufferPtr !== 0) {
        libopenmpt._free(this.leftBufferPtr);
        this.leftBufferPtr = 0;
      }
      if (this.rightBufferPtr !== 0) {
        libopenmpt._free(this.rightBufferPtr);
        this.rightBufferPtr = 0;
      }
    };
    processNode.stop = function() {
      this.disconnect();
      this.cleanup();
    };
    processNode.pause = function() {
      this.paused = true;
    };
    processNode.unpause = function() {
      this.paused = false;
    };
    processNode.togglePause = function() {
      this.paused = !this.paused;
    };
    processNode.getProcessTime = function() {
      var max = this.perf.max;
      this.perf.max = 0;
      return { 'current': this.perf.current, 'max': max };
    };
    processNode.onaudioprocess = function(e) {
      var startTimeP1 = performance.now();
      var outputL = e.outputBuffer.getChannelData(0);
      var outputR = e.outputBuffer.getChannelData(1);
      var framesToRender = outputL.length;
      if (this.ModulePtr === 0) {
        for (var i = 0; i < framesToRender; ++i) {
          outputL[i] = 0;
          outputR[i] = 0;
        }
        this.disconnect();
        this.cleanup();
        return;
      }
      if (this.paused) {
        for (var i = 0; i < framesToRender; ++i) {
          outputL[i] = 0;
          outputR[i] = 0;
        }
        return;
      }
      var framesRendered = 0;
      var ended = false;
      var error = false;
      var currentPattern = libopenmpt._openmpt_module_get_current_pattern(this.modulePtr);
      var currentRow = libopenmpt._openmpt_module_get_current_row(this.modulePtr);
      startTimeP1 = startTimeP1 - performance.now();
      if (currentPattern !== this.patternIndex) {
        processNode.player.fireEvent('onPatternChange');
      }
      processNode.player.fireEvent('onRowChange', { index: currentRow });
      var startTimeP2 = performance.now();
      while (framesToRender > 0) {
        var framesPerChunk = Math.min(framesToRender, maxFramesPerChunk);
        var actualFramesPerChunk = libopenmpt._openmpt_module_read_float_stereo(this.modulePtr, this.context.sampleRate, framesPerChunk, this.leftBufferPtr, this.rightBufferPtr);
        if (actualFramesPerChunk === 0) {
          ended = true;
          // modulePtr will be 0 on openmpt: error: openmpt_module_read_float_stereo: ERROR: module * not valid or other openmpt error
          error = !this.modulePtr;
        }
        var rawAudioLeft = libopenmpt.HEAPF32.subarray(this.leftBufferPtr / 4, this.leftBufferPtr / 4 + actualFramesPerChunk);
        var rawAudioRight = libopenmpt.HEAPF32.subarray(this.rightBufferPtr / 4, this.rightBufferPtr / 4 + actualFramesPerChunk);
        for (var i = 0; i < actualFramesPerChunk; ++i) {
          outputL[framesRendered + i] = rawAudioLeft[i];
          outputR[framesRendered + i] = rawAudioRight[i];
        }
        for (var i = actualFramesPerChunk; i < framesPerChunk; ++i) {
          outputL[framesRendered + i] = 0;
          outputR[framesRendered + i] = 0;
        }
        framesToRender -= framesPerChunk;
        framesRendered += framesPerChunk;
      }
      if (ended) {
        this.disconnect();
        this.cleanup();
        error ? processNode.player.fireEvent('onError', { type: 'openmpt' }) : processNode.player.fireEvent('onEnded');
      }
      this.perf.current = performance.now() - startTimeP2 + startTimeP1;
      if (this.perf.current > this.perf.max)
        this.perf.max = this.perf.current;
    };
    return processNode;
  }
};