/*!
 * Copyright (c) 2017-2018 by The Funfix Project Developers.
 * Some rights reserved.
 *
 * 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.
 */

/* @flow */

import type { Throwable } from "funfix-core"
import { Duration } from "./time"
import { Cancelable } from "./cancelable"
import { DynamicRef } from "./ref"

declare export class Scheduler {
  /** @protected */
  constructor(em: ExecutionModel): Scheduler;

  batchIndex: number;

  executeBatched(runnable: () => void): void;
  executeAsync(runnable: () => void): void;
  trampoline(runnable: () => void): void;

  reportFailure(e: Throwable): void;
  currentTimeMillis(): number;

  scheduleOnce(delay: number | Duration, runnable: () => void): Cancelable;
  scheduleWithFixedDelay(initialDelay: number | Duration, delay: number | Duration, runnable: () => void): Cancelable;
  scheduleAtFixedRate(initialDelay: number | Duration, period: number | Duration, runnable: () => void): Cancelable;

  +executionModel: ExecutionModel;
  withExecutionModel(em: ExecutionModel): Scheduler;

  static +global: DynamicRef<Scheduler>;
}

declare export class TestScheduler extends Scheduler {
  constructor(reporter?: (error: any) => void, em?: ExecutionModel): TestScheduler;

  triggeredFailures(): Array<any>;
  hasTasksLeft(): boolean;
  tick(duration?: number | Duration): number;
  tickOne(): boolean;
}

declare export class GlobalScheduler extends Scheduler {
  constructor(canUseSetImmediate?: boolean, em?: ExecutionModel, reporter?: (e: Throwable) => void): GlobalScheduler;
}

declare export class ExecutionModel {
  recommendedBatchSize: number;
  type: "batched" | "synchronous" | "alwaysAsync";

  equals(other: ExecutionModel): boolean;
  hashCode(): number;

  static synchronous(): ExecutionModel;
  static alwaysAsync(): ExecutionModel;
  static batched(recommendedBatchSize?: number): ExecutionModel;

  static +global: DynamicRef<ExecutionModel>;
}
