/**
     * Get the HTTP options for the requests
     *
     * @returns {HttpOptions}
     */
private getOptions(data?) {
        let headers = new HttpHeaders();
            headers = headers.append('Authorization', `Bearer ${this.token.access_token}`);

        const options = {
            headers: headers,
            observe: 'body',
            params: (data) ? new HttpParams({
                fromObject: data
            }) : new HttpParams(),
            reportProgress: true,
            responseType: 'json',
            withCredentials: true
        };

        return options;
    }


(id: number): IncrementAction => {
  return { type: Types.INCREMENT_PROGRESS, payload: id };
}


(id: number): DecrementAction => {
  return { type: Types.DECREMENT_PROGRESS, payload: id };
}


(state: AppState = initialState, action: AppActions) => {
  console.log(`[#${action.type}]`);
  switch (action.type) {
    case Types.INCREMENT_PROGRESS: {
      const okr = { ...state.okr };
      const keyResults = [...okr.keyResults];
      const idx = keyResults.findIndex((i) => i.id === action.payload);
      if (idx !== -1) {
        if (keyResults[idx].completedTasks < keyResults[idx].totalTasks)
          keyResults[idx].completedTasks++;
      }
      okr.keyResults = keyResults;
      return { ...state, okr };
    }
    case Types.DECREMENT_PROGRESS: {
      const okr = { ...state.okr };
      const keyResults = [...okr.keyResults];
      const idx = keyResults.findIndex((i) => i.id === action.payload);
      if (idx !== -1) {
        if (keyResults[idx].completedTasks > 0)
          keyResults[idx].completedTasks--;
      }
      okr.keyResults = keyResults;
      return { ...state, okr };
    }
    default: {
      return state;
    }
  }
}


(i) => i.id === action.payload


export interface KeyResult {
  id: number;
  title: string;
  totalTasks: number;
  completedTasks: number;
}


export interface AtomicOKR {
  id: number;
  objective: string;
  description: string;
  keyResults: KeyResult[];
}


export interface AppState {
  okr: AtomicOKR;
}


export enum Types {
  INCREMENT_PROGRESS = 'INCREMENT_PROGRESS',
  DECREMENT_PROGRESS = 'DECREMENT_PROGRESS',
}


type IncrementAction = { type: Types.INCREMENT_PROGRESS; payload: number };


type DecrementAction = { type: Types.DECREMENT_PROGRESS; payload: number };


type AppActions = IncrementAction | DecrementAction;


() => {
  const ShowStat = () => {
    return (
      <>
        <Column>
          <Row>Stat</Row>
        </Column>
      </>
    )
  }

  return (
    <Page>
      <ShowcaseHeader
        title="Stat"
        description={`
          Show data in a number or a graphical visual.
        `}


() => {
    return (
      <>
        <Column>
          <Row>Stat</Row>
        </Column>
      </>
    )
  }


(transformType) => {
        if (transformType === 'trim') {
          value = value.trim();
        } else if (transformType === 'toLowerCase') {
          value = value.toLowerCase();
        } else if (transformType === 'toUpperCase') {
          value = value.toUpperCase();
        }
      }


(msg) => {
                this.props.onValidate?.(msg);
                return msg;
              }


(error) => { throw error; }


export default class InputComponent extends React.PureComponent<Props> {
  public static componentName = 'input';

  private transform(value: string) {
    const transform = (this.props.schema as StringDataSchema).transform;
    if (transform) {
      transform.forEach((transformType) => {
        if (transformType === 'trim') {
          value = value.trim();
        } else if (transformType === 'toLowerCase') {
          value = value.toLowerCase();
        } else if (transformType === 'toUpperCase') {
          value = value.toUpperCase();
        }
      });
    }
    return value;
  }

  public render() {
    const config = this.props.schema;
    const uiProps = this.props.schema['ui:props'] || {};

    return (
      <Input
        {...uiProps}
        value={this.props.value as string}
        placeholder={uiProps.placeholder as string}
        disabled={uiProps.disabled as boolean}
        style={{ width: 420, ...uiProps.style }}
        onChange={(e) =>


interface Props {
  schema: DTGComponentPropertySchema;
  value?: string;
  onChange?: (value: string) => void;
  onValidate?: (errorMessage: string) => void;
}


private transform(value: string) {
    const transform = (this.props.schema as StringDataSchema).transform;
    if (transform) {
      transform.forEach((transformType) => {
        if (transformType === 'trim') {
          value = value.trim();
        } else if (transformType === 'toLowerCase') {
          value = value.toLowerCase();
        } else if (transformType === 'toUpperCase') {
          value = value.toUpperCase();
        }
      });
    }
    return value;
  }


public render() {
    const config = this.props.schema;
    const uiProps = this.props.schema['ui:props'] || {};

    return (
      <Input
        {...uiProps}
        value={this.props.value as string}
        placeholder={uiProps.placeholder as string}
        disabled={uiProps.disabled as boolean}
        style={{ width: 420, ...uiProps.style }}


(_testName, C, domTarget) => {
  const Component = C as InteractiveType
  const prefix = domTarget ? 'dom-' : ''
  const { getByTestId, rerender } = render(<Component gestures={['Hover']} />)
  const element = getByTestId(`${prefix}hover-el`)

  test('mouseEnter should initiate hover', () => {
    fireEvent.mouseEnter(element, { clientX: 10, clientY: 20 })
    expect(getByTestId(`${prefix}hover-hovering`)).toHaveTextContent('true')
    expect(getByTestId(`${prefix}hover-xy`)).toHaveTextContent('10,20')
  })

  test('mouseLeave should terminate hover', () => {
    fireEvent.mouseLeave(element, { clientX: 20, clientY: 40 })
    expect(getByTestId(`${prefix}hover-hovering`)).toHaveTextContent('false')
    expect(getByTestId(`${prefix}hover-xy`)).toHaveTextContent('20,40')
  })

  test('disabling all gestures should prevent state from updating', () => {
    rerender(<Component gestures={['Hover']} config={{ enabled: false }} />)
    fireEvent.mouseEnter(element)
    expect(getByTestId(`${prefix}hover-hovering`)).toHaveTextContent('false')
  }


() => {
    fireEvent.mouseEnter(element, { clientX: 10, clientY: 20 })
    expect(getByTestId(`${prefix}hover-hovering`)).toHaveTextContent('true')
    expect(getByTestId(`${prefix}hover-xy`)).toHaveTextContent('10,20')
  }


() => {
    fireEvent.mouseLeave(element, { clientX: 20, clientY: 40 })
    expect(getByTestId(`${prefix}hover-hovering`)).toHaveTextContent('false')
    expect(getByTestId(`${prefix}hover-xy`)).toHaveTextContent('20,40')
  }


() => {
    rerender(<Component gestures={['Hover']} config={{ enabled: false }}


() => {
    rerender(<Component gestures={['Hover']} config={{ hover: { enabled: false } }}


() => {
  // registerでバリデーション
  // errorsでバリデーションエラーのハンドリング
  // handleSubmitで送信
  const { register, errors, handleSubmit, watch } = useForm<Inputs>({
    // 初回バリデーションのタイミング(mode)をonBlurに設定
    mode: "onBlur"
  });

  // 投稿画像のstateを設定
  const [photos, setPhotos] = useState<File[]>([]);
  const [address, setAddress] = useState("");
  const [show, setShow] = useState(false);

  // const modalOn = () => setShow(true);

  const onSubmit = async (data: Inputs): Promise<void> => {
    console.log(data);
    const { name, comment, tags} = data;
    if (
      name === "" &&
      comment === "" &&
      tags === "" &&
      photos.length === 0
    ) {
      // アンケートフォームが空の場合はPOSTしない
      return;
    }

    // 画像を送信できるようにFormDataに変換する
    const formData = new FormData();
    // appendでformDataにキーと値を追加
    formData.append("name", name);
    formData.append("comment", comment);
    formData.append("address", address);
    formData.append("tags", tags);
    const compressOptions = {
      // 3MB以下に圧縮する
      maxSizeMB: 3,
    };
    // Promise.all で 非同期処理を実行し値を代入
    const compressedPhotoData = await Promise.all(
      // 一枚一枚の順番を変えないため改めてasyncで処理をハンドリング
      photos.map(async (photo) => {
        return {
          blob: await imageCompression(photo, compressOptions)
        };
      })
    );
    // console.log(compressedPhotoData);

    for (let i = 0; i < compressedPhotoData.length; i++){
      formData.append("place_image_" + i, compressedPhotoData[i].blob,
      );

     }

    // 以下 一枚の写真しか送れなかったもの
    // forEachで圧縮した写真データphotoDataとして渡し一つずつformDataに入れる
    // compressedPhotoData.forEach((photoData) => {
    //   formData.append("place_image", photoData.blob, photoData.name);
    // });
    console.log(...formData.entries());
// axiosの記述方法 postメソッドを使わないやり方で記述
    axios({
      // php側のstoreメソッドのルートのurl
      url: "/place",
      method: "post",
      data: formData,
      // formの送信時のenctype
      headers: {
        "content-type": "multipart/form-data",
      },
    })
      .then(() => {
        // ここにモーダルコンポーネント
        setShow(true);
      })
      .catch(() => {
        alert("エラーが発生しました。");

      });
  };
// スタイル
    const useStyles = makeStyles(() =>
    createStyles({
        "dataContainer": {
        borderColor: 'red'
        },
        "photoUpload": {
      },
      "AddressUpload": {},
      "tagsUpload": {},
        "button": {
        }

    }))
  const classes = useStyles();
  // html
  return (
    <>
      <form onSubmit={handleSubmit(onSubmit)}>

        場所の名前
        <input
          name="name"
          // refのなかにバリデーションルールを記述
          ref={register({required : true, maxLength: 30 })}
          // error={errors.name !== undefined}
          />
          {errors.address && 文字数は最大30文字です}
        コメント
        <input
            name="comment"
            ref={register({ required: true, maxLength: 200 })}
          />
          {errors.comment && 文字数は最大200文字です}

        {/* PostalCodeで値を紐付ける必要がある  */}
        <PostalCode name="address" address={address} setAddress={setAddress} />

        {/* propsでphotosのstateをわたす */}
            <PhotosUpload name="photos" photos={photos} setPhotos={setPhotos} />

        タグ
        <input
          name="tags"
          ref={register()}
        />

        <input type="submit" />

        {/* <button disabled={ } /> */}

      </form>
      <NewModal show={show} />

    </>


async (data: Inputs): Promise<void> => {
    console.log(data);
    const { name, comment, tags} = data;
    if (
      name === "" &&
      comment === "" &&
      tags === "" &&
      photos.length === 0
    ) {
      // アンケートフォームが空の場合はPOSTしない
      return;
    }

    // 画像を送信できるようにFormDataに変換する
    const formData = new FormData();
    // appendでformDataにキーと値を追加
    formData.append("name", name);
    formData.append("comment", comment);
    formData.append("address", address);
    formData.append("tags", tags);
    const compressOptions = {
      // 3MB以下に圧縮する
      maxSizeMB: 3,
    };
    // Promise.all で 非同期処理を実行し値を代入
    const compressedPhotoData = await Promise.all(
      // 一枚一枚の順番を変えないため改めてasyncで処理をハンドリング
      photos.map(async (photo) => {
        return {
          blob: await imageCompression(photo, compressOptions)
        };
      })
    );
    // console.log(compressedPhotoData);

    for (let i = 0; i < compressedPhotoData.length; i++){
      formData.append("place_image_" + i, compressedPhotoData[i].blob,
      );

     }

    // 以下 一枚の写真しか送れなかったもの
    // forEachで圧縮した写真データphotoDataとして渡し一つずつformDataに入れる
    // compressedPhotoData.forEach((photoData) => {
    //   formData.append("place_image", photoData.blob, photoData.name);
    // });
    console.log(...formData.entries());
// axiosの記述方法 postメソッドを使わないやり方で記述
    axios({
      // php側のstoreメソッドのルートのurl
      url: "/place",
      method: "post",
      data: formData,
      // formの送信時のenctype
      headers: {
        "content-type": "multipart/form-data",
      },
    })
      .then(() => {
        // ここにモーダルコンポーネント
        setShow(true);
      })
      .catch(() => {
        alert("エラーが発生しました。");

      });
  }


async (photo) => {
        return {
          blob: await imageCompression(photo, compressOptions)
        };
      }


() => {
        // ここにモーダルコンポーネント
        setShow(true);
      }


() => {
        alert("エラーが発生しました。");

      }


() =>
    createStyles({
        "dataContainer": {
        borderColor: 'red'
        },
        "photoUpload": {
      },
      "AddressUpload": {},
      "tagsUpload": {},
        "button": {
        }

    })


// 型定義
interface Inputs {
  name: string;
  comment: string;
  address: string;
  tags: string;
}


register({required : true, maxLength: 30 })


register({ required: true, maxLength: 200 })


register()


// Extend the generic Workflow interface to check that Example is a valid workflow interface
// Workflow interfaces are useful for generating type safe workflow clients
export interface Example extends Workflow {
  main(name: string): Promise<string>;
}


async function timeOut(message: string, timeout: number): Promise<void> {
  return new Promise((resolve, reject) => {
    const timer = setTimeout(() => reject(`${message} Timeout after ${timeout}ms`), timeout);
    timer.unref();
  });
}


function getJson<T>(s: string): T | null {
  try {
    return JSON.parse(s);
  } catch (e) {
    return null;
  }
}


(resolve, reject) => {
    const timer = setTimeout(() => reject(`${message} Timeout after ${timeout}ms`), timeout);
    timer.unref();
  }


() => reject(`${message} Timeout after ${timeout}ms`)


async (resolve) => {
      const process = spawn(WineCommand, args, { cwd });
      if (process == null || process.stdout == null) throw new Error('Failed to start command');
      this.process = process;
      process.stderr.on('data', (data) => {
        Log.debug({ data: data.toString().trim() }, 'MapProcess:stderr');
      });
      process.on('error', (error) => {
        log.fatal({ error }, 'ProcessDied');
        inter.close();
        this.process = null;
      });
      process.on('close', (exitCode) => {
        inter.close();
        this.process = null;
        if (exitCode == null) return;
        if (exitCode > 0) log.fatal({ exitCode }, 'ProcessClosed');
      });

      log.info({ pid: process.pid }, 'MapProcessStarted');
      const inter = createInterface(process.stdout).on('line', (line) => {
        const json = getJson<Diablo2MapGenMessage | LogMessage>(line);
        if (json == null) return;
        if ('time' in json) {
          if (json.level < 30) return;
          Log.info({ ...json, log: json.msg }, 'SubProcess');
        } else if (json.type) this.events.emit(json.type, json);
      });
      await this.once('init');
      resolve();
    }


(data) => {
        Log.debug({ data: data.toString().trim() }, 'MapProcess:stderr');
      }


(error) => {
        log.fatal({ error }, 'ProcessDied');
        inter.close();
        this.process = null;
      }


(exitCode) => {
        inter.close();
        this.process = null;
        if (exitCode == null) return;
        if (exitCode > 0) log.fatal({ exitCode }, 'ProcessClosed');
      }


(line) => {
        const json = getJson<Diablo2MapGenMessage | LogMessage>(line);
        if (json == null) return;
        if ('time' in json) {
          if (json.level < 30) return;
          Log.info({ ...json, log: json.msg }, 'SubProcess');
        } else if (json.type) this.events.emit(json.type, json);
      }


(resolve) => {
        this.events.once(e, (data) => resolve(data));
        cb?.();
      }


(data) => resolve(data)


() => this.process?.stdin?.write(command)


async () => {
      const mapResult = await this.getMaps(seed, difficulty, log);
      this.cache.set(mapKey, mapResult);
      return mapResult;
    }


(msg: MapGenMessageMap): void => {
      log.trace({ mapId: msg.id }, 'GotMap');
      maps[msg.id] = msg;
    }


(resolve, reject) => {
      const failedTimer = setTimeout(() => {
        this.events.off('map', newMap);
        reject();
      }, ProcessTimeout);
      this.events.on('map', newMap);
      this.events.on('done', () => {
        this.events.off('map', newMap);
        clearTimeout(failedTimer);
        log.trace({ count: Object.keys(maps).length }, 'MapsGenerated');
        resolve(maps);
      });
      this.process?.stdin?.write(`$map\n`);
    }


() => {
        this.events.off('map', newMap);
        reject();
      }


() => {
        this.events.off('map', newMap);
        clearTimeout(failedTimer);
        log.trace({ count: Object.keys(maps).length }, 'MapsGenerated');
        resolve(maps);
      }


export class Diablo2MapProcess {
  cache: LruCache<Diablo2MapResponse> = new LruCache(100);
  process: ChildProcess | null;
  /** Number of maps generated by this process */
  generatedCount = 0;
  events: EventEmitter = new EventEmitter();
  /**
   * Limit the map generation to a single thread
   * TODO having a pool of these map processes would be quite nice
   */
  q = PLimit(1);

  /** Get the version of WINE that is being used */
  async version(log: LogType): Promise<string> {
    const versionResponse = spawnSync(WineCommand, ['--version']);
    const version = versionResponse.stdout.toString().trim();
    log.info({ version, command: WineCommand }, 'WineVersion');
    return version;
  }

  /** Start the map process waiting for the `init` event before allowing anything to continue */
  async start(log: LogType): Promise<void> {
    if (this.process != null) {
      Log.warn({ pid: this.process.pid }, 'MapProcess already started');
      return;
    }
    this.generatedCount = 0;

    const res = spawnSync(WineCommand, ['regedit', RegistryPath]);
    log.info({ data: res.stdout.toString() }, 'RegistryUpdate');

    // const gamePath = await this.getGamePath();
    const args = [MapCommand, Diablo2Path];
    log.info({ wineArgs: args }, 'Starting MapProcess');

    return new Promise(async (resolve) => {
      const process = spawn(WineCommand, args, { cwd });
      if (process == null || process.stdout == null) throw new Error('Failed to start command');
      this.process = process;
      process.stderr.on('data', (data) => {
        Log.debug({ data: data.toString().trim() }, 'MapProcess:stderr');
      });
      process.on('error', (error) => {
        log.fatal({ error }, 'ProcessDied');
        inter.close();
        this.process = null;
      });
      process.on('close', (exitCode) => {
        inter.close();
        this.process = null;
        if (exitCode == null) return;
        if (exitCode > 0) log.fatal({ exitCode }, 'ProcessClosed');
      });

      log.info({ pid: process.pid }, 'MapProcessStarted');
      const inter = createInterface(process.stdout).on('line', (line) => {
        const json = getJson<Diablo2MapGenMessage | LogMessage>(line);
        if (json == null) return;
        if ('time' in json) {
          if (json.level < 30) return;
          Log.info({ ...json, log: json.msg }, 'SubProcess');
        } else if (json.type) this.events.emit(json.type, json);
      });
      await this.once('init');
      resolve();
    });
  }

  async once<T extends Diablo2MapGenMessage>(e: T['type'], cb?: () => void): Promise<T> {
    return Promise.race([
      new Promise((resolve) => {
        this.events.once(e, (data) => resolve(data));
        cb?.();
      }),
      timeOut(`Event: ${e}`, ProcessTimeout),
    ]) as Promise<T>;
  }

  async stop(log: LogType): Promise<void> {
    if (this.process == null) return;
    log.info({ pid: this.process.pid }, 'StoppingProcess');
    this.process.kill('SIGKILL');
    this.process = null;
  }

  async command(cmd: 'seed' | 'difficulty', value: number, log: LogType): Promise<void> {
    if (this.process == null) await this.start(log);
    log.info({ cmd, value }, 'Command');
    const command = `$${cmd} ${value}\n`;
    const res = await this.once<MapGenMessageInfo>('info', () => this.process?.stdin?.write(command));
    if (res[cmd] !== value)
      throw new Error(`Failed to set ${cmd}=${value} (output: ${JSON.stringify(res)}: ${command})`);
  }

  map(seed: number, difficulty: number, log: LogType): Promise<Diablo2MapResponse> {
    const mapKey = `${seed}_${difficulty}`;
    const cacheData = this.cache.get(mapKey);
    if (cacheData != null) return Promise.resolve(cacheData);
    return this.q(async () => {
      const mapResult = await this.getMaps(seed, difficulty, log);
      this.cache.set(mapKey, mapResult);
      return mapResult;
    });
  }

  private async getMaps(seed: number, difficulty: number, log: LogType): Promise<Diablo2MapResponse> {
    if (this.generatedCount > MaxMapsToGenerate) {
      this.generatedCount = 0;
      await this.stop(log);
      await this.start(log);
    }

    await this.command('seed', seed, log);
    await this.command('difficulty', difficulty, log);

    this.generatedCount++;
    log.info({ seed, difficulty, generated: this.generatedCount }, 'GenerateMap');
    const maps: Record<string, Diablo2Map> = {};

    const newMap = (msg: MapGenMessageMap): void => {
      log.trace({ mapId: msg.id }, 'GotMap');
      maps[msg.id] = msg;
    };

    return await new Promise((resolve, reject) => {
      const failedTimer = setTimeout(() => {
        this.events.off('map', newMap);
        reject();
      }, ProcessTimeout);
      this.events.on('map', newMap);
      this.events.on('done', () => {
        this.events.off('map', newMap);
        clearTimeout(failedTimer);
        log.trace({ count: Object.keys(maps).length }, 'MapsGenerated');
        resolve(maps);
      });
      this.process?.stdin?.write(`$map\n`);
    });
  }
}


interface LogMessage {
  time: number;
  level: number;
  msg: string;
}


export type Diablo2MapResponse = { [key: string]: Diablo2Map };


/** Get the version of WINE that is being used */
async version(log: LogType): Promise<string> {
    const versionResponse = spawnSync(WineCommand, ['--version']);
    const version = versionResponse.stdout.toString().trim();
    log.info({ version, command: WineCommand }, 'WineVersion');
    return version;
  }


/** Start the map process waiting for the `init` event before allowing anything to continue */
async start(log: LogType): Promise<void> {
    if (this.process != null) {
      Log.warn({ pid: this.process.pid }, 'MapProcess already started');
      return;
    }
    this.generatedCount = 0;

    const res = spawnSync(WineCommand, ['regedit', RegistryPath]);
    log.info({ data: res.stdout.toString() }, 'RegistryUpdate');

    // const gamePath = await this.getGamePath();
    const args = [MapCommand, Diablo2Path];
    log.info({ wineArgs: args }, 'Starting MapProcess');

    return new Promise(async (resolve) => {
      const process = spawn(WineCommand, args, { cwd });
      if (process == null || process.stdout == null) throw new Error('Failed to start command');
      this.process = process;
      process.stderr.on('data', (data) => {
        Log.debug({ data: data.toString().trim() }, 'MapProcess:stderr');
      });
      process.on('error', (error) => {
        log.fatal({ error }, 'ProcessDied');
        inter.close();
        this.process = null;
      });
      process.on('close', (exitCode) => {
        inter.close();
        this.process = null;
        if (exitCode == null) return;
        if (exitCode > 0) log.fatal({ exitCode }, 'ProcessClosed');
      });

      log.info({ pid: process.pid }, 'MapProcessStarted');
      const inter = createInterface(process.stdout).on('line', (line) => {
        const json = getJson<Diablo2MapGenMessage | LogMessage>(line);
        if (json == null) return;
        if ('time' in json) {
          if (json.level < 30) return;
          Log.info({ ...json, log: json.msg }, 'SubProcess');
        } else if (json.type) this.events.emit(json.type, json);
      });
      await this.once('init');
      resolve();
    });
  }


async once<T extends Diablo2MapGenMessage>(e: T['type'], cb?: () => void): Promise<T> {
    return Promise.race([
      new Promise((resolve) => {
        this.events.once(e, (data) => resolve(data));
        cb?.();
      }),
      timeOut(`Event: ${e}`, ProcessTimeout),
    ]) as Promise<T>;
  }


async stop(log: LogType): Promise<void> {
    if (this.process == null) return;
    log.info({ pid: this.process.pid }, 'StoppingProcess');
    this.process.kill('SIGKILL');
    this.process = null;
  }


async command(cmd: 'seed' | 'difficulty', value: number, log: LogType): Promise<void> {
    if (this.process == null) await this.start(log);
    log.info({ cmd, value }, 'Command');
    const command = `$${cmd} ${value}\n`;
    const res = await this.once<MapGenMessageInfo>('info', () => this.process?.stdin?.write(command));
    if (res[cmd] !== value)
      throw new Error(`Failed to set ${cmd}=${value} (output: ${JSON.stringify(res)}: ${command})`);
  }


map(seed: number, difficulty: number, log: LogType): Promise<Diablo2MapResponse> {
    const mapKey = `${seed}_${difficulty}`;
    const cacheData = this.cache.get(mapKey);
    if (cacheData != null) return Promise.resolve(cacheData);
    return this.q(async () => {
      const mapResult = await this.getMaps(seed, difficulty, log);
      this.cache.set(mapKey, mapResult);
      return mapResult;
    });
  }


private async getMaps(seed: number, difficulty: number, log: LogType): Promise<Diablo2MapResponse> {
    if (this.generatedCount > MaxMapsToGenerate) {
      this.generatedCount = 0;
      await this.stop(log);
      await this.start(log);
    }

    await this.command('seed', seed, log);
    await this.command('difficulty', difficulty, log);

    this.generatedCount++;
    log.info({ seed, difficulty, generated: this.generatedCount }, 'GenerateMap');
    const maps: Record<string, Diablo2Map> = {};

    const newMap = (msg: MapGenMessageMap): void => {
      log.trace({ mapId: msg.id }, 'GotMap');
      maps[msg.id] = msg;
    };

    return await new Promise((resolve, reject) => {
      const failedTimer = setTimeout(() => {
        this.events.off('map', newMap);
        reject();
      }, ProcessTimeout);
      this.events.on('map', newMap);
      this.events.on('done', () => {
        this.events.off('map', newMap);
        clearTimeout(failedTimer);
        log.trace({ count: Object.keys(maps).length }, 'MapsGenerated');
        resolve(maps);
      });
      this.process?.stdin?.write(`$map\n`);
    });
  }


export default function PostIframe(value: any) {
  console.error('PostIframe', value)
  return <iframe width={680} src={value.src} frameBorder="0"
                       allowFullScreen/>
}


export interface IProps {
  children: React.ReactChild
  href: string;
}


() => {
  let component: GettingStartedComponent;
  let fixture: ComponentFixture<GettingStartedComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [GettingStartedComponent]
    })
      .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(GettingStartedComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
}


() => {
    TestBed.configureTestingModule({
      declarations: [GettingStartedComponent]
    })
      .compileComponents();
  }


() => {
    fixture = TestBed.createComponent(GettingStartedComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  }


/**
 * TODO: Implement this component
 */
function AppBarSection({ item }: { item: LandingBarItem }): JSX.Element {
  return
{item}
;
}


/**
 *
 */
export default function LandingAppBar(props: LandingAppBarProps): JSX.Element {
  const {} = props;
  return <nav className="p-4"></nav>;
}


/**
 * Component properties for a LandingAppBar.
 */
interface LandingAppBarProps {
  items: LandingBarItem;
}


type LandingBarItem = {
  title: string;
  href: string;
};


() => {
  describe('Component', () => {
    it('render', async () => {
      const page = await newE2EPage()
      await page.setContent(
        `<webc-modal>

Hello world

        </webc-modal>`
      )
      const component = await page.find(COMPONENT_NAME)
      expect(component).toHaveClass('hydrated')
    })
  })

  describe('Methods', () => {
    it('show()', async () => {
      const page = await newE2EPage()
      await page.setContent(
        `<webc-modal>

Hello world

        </webc-modal>`
      )
      const component = await page.find(COMPONENT_NAME)
      const rootElement = await page.find(ROOT_ELEMENT)
      expect(rootElement).not.toHaveClass('show')

      await component.callMethod('show')
      await page.waitForChanges()
      expect(rootElement).toHaveClass('show')
    })

    it('hide()', async () => {
      const page = await newE2EPage()
      await page.setContent(
        `<webc-modal>

Hello world

        </webc-modal>`
      )
      const component = await page.find(COMPONENT_NAME)
      const rootElement = await page.find(ROOT_ELEMENT)

      await component.callMethod('show')
      await page.waitForChanges()
      expect(rootElement).toHaveClass('show')

      await component.callMethod('hide')
      await page.waitForChanges()
      expect(rootElement).not.toHaveClass('show')
    })
  })
}


() => {
    it('render', async () => {
      const page = await newE2EPage()
      await page.setContent(
        `<webc-modal>

Hello world

        </webc-modal>`
      )
      const component = await page.find(COMPONENT_NAME)
      expect(component).toHaveClass('hydrated')
    })
  }


async () => {
      const page = await newE2EPage()
      await page.setContent(
        `<webc-modal>

Hello world

        </webc-modal>`
      )
      const component = await page.find(COMPONENT_NAME)
      expect(component).toHaveClass('hydrated')
    }


() => {
    it('show()', async () => {
      const page = await newE2EPage()
      await page.setContent(
        `<webc-modal>

Hello world

        </webc-modal>`
      )
      const component = await page.find(COMPONENT_NAME)
      const rootElement = await page.find(ROOT_ELEMENT)
      expect(rootElement).not.toHaveClass('show')

      await component.callMethod('show')
      await page.waitForChanges()
      expect(rootElement).toHaveClass('show')
    })

    it('hide()', async () => {
      const page = await newE2EPage()
      await page.setContent(
        `<webc-modal>

Hello world

        </webc-modal>`
      )
      const component = await page.find(COMPONENT_NAME)
      const rootElement = await page.find(ROOT_ELEMENT)

      await component.callMethod('show')
      await page.waitForChanges()
      expect(rootElement).toHaveClass('show')

      await component.callMethod('hide')
      await page.waitForChanges()
      expect(rootElement).not.toHaveClass('show')
    })
  }


async () => {
      const page = await newE2EPage()
      await page.setContent(
        `<webc-modal>

Hello world

        </webc-modal>`
      )
      const component = await page.find(COMPONENT_NAME)
      const rootElement = await page.find(ROOT_ELEMENT)
      expect(rootElement).not.toHaveClass('show')

      await component.callMethod('show')
      await page.waitForChanges()
      expect(rootElement).toHaveClass('show')
    }


async () => {
      const page = await newE2EPage()
      await page.setContent(
        `<webc-modal>

Hello world

        </webc-modal>`
      )
      const component = await page.find(COMPONENT_NAME)
      const rootElement = await page.find(ROOT_ELEMENT)

      await component.callMethod('show')
      await page.waitForChanges()
      expect(rootElement).toHaveClass('show')

      await component.callMethod('hide')
      await page.waitForChanges()
      expect(rootElement).not.toHaveClass('show')
    }


export class Schueler {
  name: string;
  gruppenId?: string;
}


export type SchuelerDocument = Schueler & Document;


(msg: Message) => {
  const dataHash = utils.solidityKeccak256(['bytes'], [msg.data]);
  return utils.solidityKeccak256(
    ['address', 'address', 'uint256', 'bytes32', 'uint256', 'uint', 'address', 'uint', 'uint'],
    [msg.from, msg.to, msg.value, dataHash, msg.nonce, msg.gasPrice, msg.gasToken, msg.gasLimit, msg.operationType]);
}


(privateKey: string, msg: Message) => {
  const wallet = new Wallet(privateKey);
  const massageHash = calculateMessageHash(msg);
  return wallet.signMessage(utils.arrayify(massageHash));
}


export interface Message {
  from: string;
  to: string;
  value: utils.BigNumberish;
  data: string;
  nonce: utils.BigNumberish;
  gasPrice: utils.BigNumberish;
  gasToken: string;
  gasLimit: utils.BigNumberish;
  operationType: utils.BigNumberish;
}


export class AttachCertificateToDistributionCommand extends $Command<
  AttachCertificateToDistributionCommandInput,
  AttachCertificateToDistributionCommandOutput,
  LightsailClientResolvedConfig
> {
  // Start section: command_properties
  // End section: command_properties

  constructor(readonly input: AttachCertificateToDistributionCommandInput) {
    // Start section: command_constructor
    super();
    // End section: command_constructor
  }

  resolveMiddleware(
    clientStack: MiddlewareStack<ServiceInputTypes, ServiceOutputTypes>,
    configuration: LightsailClientResolvedConfig,
    options?: __HttpHandlerOptions
  ): Handler<AttachCertificateToDistributionCommandInput, AttachCertificateToDistributionCommandOutput> {
    this.middlewareStack.use(getSerdePlugin(configuration, this.serialize, this.deserialize));

    const stack = clientStack.concat(this.middlewareStack);

    const { logger } = configuration;
    const handlerExecutionContext: HandlerExecutionContext = {
      logger,
      inputFilterSensitiveLog: AttachCertificateToDistributionRequest.filterSensitiveLog,
      outputFilterSensitiveLog: AttachCertificateToDistributionResult.filterSensitiveLog,
    };
    const { requestHandler } = configuration;
    return stack.resolve(
      (request: FinalizeHandlerArguments<any>) =>
        requestHandler.handle(request.request as __HttpRequest, options || {}),
      handlerExecutionContext
    );
  }

  private serialize(
    input: AttachCertificateToDistributionCommandInput,
    context: __SerdeContext
  ): Promise<__HttpRequest> {
    return serializeAws_json1_1AttachCertificateToDistributionCommand(input, context);
  }

  private deserialize(
    output: __HttpResponse,
    context: __SerdeContext
  ): Promise<AttachCertificateToDistributionCommandOutput> {
    return deserializeAws_json1_1AttachCertificateToDistributionCommand(output, context);
  }

  // Start section: command_body_extra
  // End section: command_body_extra
}


export type AttachCertificateToDistributionCommandInput = AttachCertificateToDistributionRequest;


export type AttachCertificateToDistributionCommandOutput = AttachCertificateToDistributionResult & __MetadataBearer;


resolveMiddleware(
    clientStack: MiddlewareStack<ServiceInputTypes, ServiceOutputTypes>,
    configuration: LightsailClientResolvedConfig,
    options?: __HttpHandlerOptions
  ): Handler<AttachCertificateToDistributionCommandInput, AttachCertificateToDistributionCommandOutput> {
    this.middlewareStack.use(getSerdePlugin(configuration, this.serialize, this.deserialize));

    const stack = clientStack.concat(this.middlewareStack);

    const { logger } = configuration;
    const handlerExecutionContext: HandlerExecutionContext = {
      logger,
      inputFilterSensitiveLog: AttachCertificateToDistributionRequest.filterSensitiveLog,
      outputFilterSensitiveLog: AttachCertificateToDistributionResult.filterSensitiveLog,
    };
    const { requestHandler } = configuration;
    return stack.resolve(
      (request: FinalizeHandlerArguments<any>) =>
        requestHandler.handle(request.request as __HttpRequest, options || {}),
      handlerExecutionContext
    );
  }


private serialize(
    input: AttachCertificateToDistributionCommandInput,
    context: __SerdeContext
  ): Promise<__HttpRequest> {
    return serializeAws_json1_1AttachCertificateToDistributionCommand(input, context);
  }


private deserialize(
    output: __HttpResponse,
    context: __SerdeContext
  ): Promise<AttachCertificateToDistributionCommandOutput> {
    return deserializeAws_json1_1AttachCertificateToDistributionCommand(output, context);
  }


() => {
      getTableData();
    }


() => {
      baseTableRef.value.clearScroll();
      loading.value = true;
      tableModel
        .base({
          pageSize: pageConf.pageSize,
          currentPage: pageConf.currentPage,
        })
        .then(res => {
          tableData.value = res.list;
          pageConf.total = res.total;
          loading.value = false;
        })
        .catch(err => {
          tableData.value= []
          loading.value = false;
        });
    }


res => {
          tableData.value = res.list;
          pageConf.total = res.total;
          loading.value = false;
        }


err => {
          tableData.value= []
          loading.value = false;
        }


({ row }) => (
        <el-input


e => {
      let { pageSize, currentPage, type } = e;
      if (type === "size") {
        pageConf.currentPage = 1;
        getTableData();
      } else {
        getTableData();
      }
    }


row => {
      const rows = Object.assign(row, { name: "1111" });
      baseTableRef.value.reloadRow([rows]);
    }


() => (
      <div>
        <vxe-table


({ row }) => {
                return (
                  <el-button
                    size="mini"
                    type="success"
                    onClick={handINput.bind(this, row)}
                  >
                    update
                  </el-button>
                );
              }


setup() {
    const baseTableRef = ref({} as VxeTableInstance);
    const tableData = ref([]);
    const loading = ref(false);
    const pageConf = reactive({
      pageSize: 20,
      currentPage: 1,
      total: 0,
    });
    onMounted(() => {
      getTableData();
    });
    const getTableData = () => {
      baseTableRef.value.clearScroll();
      loading.value = true;
      tableModel
        .base({
          pageSize: pageConf.pageSize,
          currentPage: pageConf.currentPage,
        })
        .then(res => {
          tableData.value = res.list;
          pageConf.total = res.total;
          loading.value = false;
        })
        .catch(err => {
          tableData.value= []
          loading.value = false;
        });
    };
    const inputSlot = {
      default: ({ row }) => (
        <el-input size="mini" v-model={row


() => {
  const props = {
    processInstance: {
      id: '538f9feb-5a14-4096-b791-2055b38da7c6',
      processId: 'travels',
      businessKey: 'Tra234',
      parentProcessInstanceId: null,
      parentProcessInstance: null,
      processName: 'travels',
      rootProcessInstanceId: null,
      roles: [],
      state: ProcessInstanceState.Error,
      addons: [
        'jobs-management',
        'prometheus-monitoring',
        'process-management'
      ],
      start: new Date('2019-10-22T03:40:44.089Z'),
      error: {
        nodeDefinitionId: '__a1e139d5-4e77-48c9-84ae-34578e9817n',
        message: 'Something went wrong'
      },
      lastUpdate: new Date('2019-10-22T03:40:44.089Z'),
      serviceUrl: 'http://localhost:4000',
      endpoint: 'http://localhost:4000',
      variables:
        '{"flight":{"arrival":"2019-10-30T22:00:00Z[UTC]","departure":"2019-10-23T22:00:00Z[UTC]","flightNumber":"MX555"},"trip":{"begin":"2019-10-23T22:00:00Z[UTC]","city":"New York","country":"US","end":"2019-10-30T22:00:00Z[UTC]","visaRequired":false},"hotel":{"address":{"city":"New York","country":"US","street":"street","zipCode":"12345"},"bookingNumber":"XX-012345","name":"Perfect hotel","phone":"09876543"},"traveller":{"address":{"city":"Berlin","country":"Germany","street":"Bakers","zipCode":"100200"},"email":"cristiano@redhat.com","firstName":"Cristiano","lastName":"Nicolai","nationality":"German"}}',
      nodes: [],
      milestones: [],
      isSelected: false,
      childProcessInstances: []
    },
    onSkipClick: jest.fn(),
    onRetryClick: jest.fn(),
    onAbortClick: jest.fn()
  };
  it('Skip click test', () => {
    let wrapper = mount(<ProcessListActionsKebab {...props} />);
    wrapper
      .find(Dropdown)
      .find(KebabToggle)
      .find('button')
      .simulate('click');
    wrapper = wrapper.update();
    expect(
      wrapper
        .find(DropdownItem)
        .at(1)
        .find('a')
        .children()
        .contains('Skip')
    ).toBeTruthy();
    wrapper
      .find(DropdownItem)
      .at(1)
      .simulate('click');
    expect(props.onSkipClick).toHaveBeenCalled();
  });

  it('Retry click test', () => {
    let wrapper = mount(<ProcessListActionsKebab {...props} />);
    wrapper
      .find(Dropdown)
      .find(KebabToggle)
      .find('button')
      .simulate('click');
    wrapper = wrapper.update();
    expect(
      wrapper
        .find(DropdownItem)
        .at(0)
        .find('a')
        .children()
        .contains('Retry')
    ).toBeTruthy();
    wrapper
      .find(DropdownItem)
      .at(0)
      .simulate('click');
    expect(props.onRetryClick).toHaveBeenCalled();
  });

  it('Abort click test', () => {
    let wrapper = mount(<ProcessListActionsKebab {...props} />);
    wrapper
      .find(Dropdown)
      .find(KebabToggle)
      .find('button')
      .simulate('click');
    wrapper = wrapper.update();
    expect(
      wrapper
        .find(DropdownItem)
        .at(2)
        .find('a')
        .children()
        .contains('Abort')
    ).toBeTruthy();
    wrapper
      .find(DropdownItem)
      .at(2)
      .simulate('click');
    expect(props.onAbortClick).toHaveBeenCalled();
  });
  it('process instance in active state', () => {
    let wrapper = mount(
      <ProcessListActionsKebab
        {...{
          ...props,
          processInstance: {
            ...props.processInstance,
            state: ProcessInstanceState.Active
          }
        }}
      />
    );
    wrapper
      .find(Dropdown)
      .find(KebabToggle)
      .find('button')
      .simulate('click');
    wrapper = wrapper.update();
    expect(wrapper.find(DropdownItem).length).toEqual(1);
    expect(
      wrapper
        .find(DropdownItem)
        .at(0)
        .find('a')
        .children()
        .contains('Abort')
    ).toBeTruthy();
    wrapper
      .find(DropdownItem)
      .at(0)
      .simulate('click');
    expect(props.onAbortClick).toHaveBeenCalled();
  });
}


() => {
    let wrapper = mount(<ProcessListActionsKebab {...props} />);
    wrapper
      .find(Dropdown)
      .find(KebabToggle)
      .find('button')
      .simulate('click');
    wrapper = wrapper.update();
    expect(
      wrapper
        .find(DropdownItem)
        .at(1)
        .find('a')
        .children()
        .contains('Skip')
    ).toBeTruthy();
    wrapper
      .find(DropdownItem)
      .at(1)
      .simulate('click');
    expect(props.onSkipClick).toHaveBeenCalled();
  }


() => {
    let wrapper = mount(<ProcessListActionsKebab {...props} />);
    wrapper
      .find(Dropdown)
      .find(KebabToggle)
      .find('button')
      .simulate('click');
    wrapper = wrapper.update();
    expect(
      wrapper
        .find(DropdownItem)
        .at(0)
        .find('a')
        .children()
        .contains('Retry')
    ).toBeTruthy();
    wrapper
      .find(DropdownItem)
      .at(0)
      .simulate('click');
    expect(props.onRetryClick).toHaveBeenCalled();
  }


() => {
    let wrapper = mount(<ProcessListActionsKebab {...props} />);
    wrapper
      .find(Dropdown)
      .find(KebabToggle)
      .find('button')
      .simulate('click');
    wrapper = wrapper.update();
    expect(
      wrapper
        .find(DropdownItem)
        .at(2)
        .find('a')
        .children()
        .contains('Abort')
    ).toBeTruthy();
    wrapper
      .find(DropdownItem)
      .at(2)
      .simulate('click');
    expect(props.onAbortClick).toHaveBeenCalled();
  }


() => {
    let wrapper = mount(
      <ProcessListActionsKebab
        {...{
          ...props,
          processInstance: {
            ...props.processInstance,
            state: ProcessInstanceState.Active
          }
        }}
      />
    );
    wrapper
      .find(Dropdown)
      .find(KebabToggle)
      .find('button')
      .simulate('click');
    wrapper = wrapper.update();
    expect(wrapper.find(DropdownItem).length).toEqual(1);
    expect(
      wrapper
        .find(DropdownItem)
        .at(0)
        .find('a')
        .children()
        .contains('Abort')
    ).toBeTruthy();
    wrapper
      .find(DropdownItem)
      .at(0)
      .simulate('click');
    expect(props.onAbortClick).toHaveBeenCalled();
  }


/**
 * Compares two currencies for equality
 */
export declare function currencyEquals(currencyA: Currency, currencyB: Currency): boolean;


/**
 * Represents an ERC20 token with a unique address and some metadata.
 */
export declare class Token extends Currency {
    readonly chainId: ChainId;
    readonly address: string;
    readonly projectLink?: string;
    constructor(chainId: ChainId, address: string, decimals: number, symbol?: string, name?: string, projectLink?: string);
    /**
     * Returns true if the two tokens are equivalent, i.e. have the same chainId and address.
     * @param other other token to compare
     */
    equals(other: Token): boolean;
    /**
     * Returns true if the address of this token sorts before the address of the other token
     * @param other other token to compare
     * @throws if the tokens have the same address
     * @throws if the tokens are on different chains
     */
    sortsBefore(other: Token): boolean;
}


/**
     * Returns true if the two tokens are equivalent, i.e. have the same chainId and address.
     * @param other other token to compare
     */
equals(other: Token): boolean;


/**
     * Returns true if the address of this token sorts before the address of the other token
     * @param other other token to compare
     * @throws if the tokens have the same address
     * @throws if the tokens are on different chains
     */
sortsBefore(other: Token): boolean;


export default function makeExpressRouterAdapter() {
  return function  expressRouterAdapter(controller, responseFormat?: string, download?: boolean) {
    return async (req: Request | any, res: Response) => {
      const httpRequest: IHttpRequest = {
        body: req.body,
        params: req.params,
        token: req.params.token,
        ref: req.params.ref,
        lang: req.params.lang,
        file: req.file
      }
      // console.log('adapt lang ', httpRequest.lang)
      const httpResponse: IHttpResponse = await controller(httpRequest)
      if(download) {
        res.type(responseFormat)
        res.status(httpResponse.statusCode).download(httpResponse.body.data)
      } else if (responseFormat === 'html') {
        res.type(responseFormat)
        res.status(httpResponse.statusCode).render(httpResponse.body.view)
      } else if (responseFormat) {
        res.type(responseFormat)
        res.status(httpResponse.statusCode).send(httpResponse.body)
      } else {
        res.status(httpResponse.statusCode).json(httpResponse.body)
      }
    }
  }
}


async (req: Request | any, res: Response) => {
      const httpRequest: IHttpRequest = {
        body: req.body,
        params: req.params,
        token: req.params.token,
        ref: req.params.ref,
        lang: req.params.lang,
        file: req.file
      }
      // console.log('adapt lang ', httpRequest.lang)
      const httpResponse: IHttpResponse = await controller(httpRequest)
      if(download) {
        res.type(responseFormat)
        res.status(httpResponse.statusCode).download(httpResponse.body.data)
      } else if (responseFormat === 'html') {
        res.type(responseFormat)
        res.status(httpResponse.statusCode).render(httpResponse.body.view)
      } else if (responseFormat) {
        res.type(responseFormat)
        res.status(httpResponse.statusCode).send(httpResponse.body)
      } else {
        res.status(httpResponse.statusCode).json(httpResponse.body)
      }
    }


({ hideLoader, onInViewport, pending }) => {
    const [inViewport, setInViewport] = useState(false)
    const [element, setElement] = useState<HTMLDivElement | null>(null)
    useEffect(() => {
        if (element) {
            const observer = new IntersectionObserver(
                entries => {
                    for (const entry of entries) {
                        if (entry.intersectionRatio > 0) {
                            setInViewport(true)
                        } else {
                            setInViewport(false)
                        }
                    }
                },
                {
                    root: null,
                    rootMargin: "200px",
                    threshold: 0,
                },
            )
            observer.observe(element)
            return () => observer.disconnect()
        }
    }, [element])
    useEffect(() => {
        if (!pending && inViewport) {
            onInViewport?.()
        }
    }, [inViewport, onInViewport, pending])
    return (
        <div className={styles.main} ref={setElement}>
            {pending && !hideLoader && <PropagateLoader color="#0080a0" />}


() => {
        if (element) {
            const observer = new IntersectionObserver(
                entries => {
                    for (const entry of entries) {
                        if (entry.intersectionRatio > 0) {
                            setInViewport(true)
                        } else {
                            setInViewport(false)
                        }
                    }
                },
                {
                    root: null,
                    rootMargin: "200px",
                    threshold: 0,
                },
            )
            observer.observe(element)
            return () => observer.disconnect()
        }
    }


entries => {
                    for (const entry of entries) {
                        if (entry.intersectionRatio > 0) {
                            setInViewport(true)
                        } else {
                            setInViewport(false)
                        }
                    }
                }


() => observer.disconnect()


() => {
        if (!pending && inViewport) {
            onInViewport?.()
        }
    }


export interface Props {
    hideLoader?: boolean
    onInViewport?: () => void
    pending?: boolean
}


(iconProps: IFluentIconsProps, props: React.HTMLAttributes<HTMLElement>): JSX.Element => {
  const {
    primaryFill,
    className
  } = iconProps;
  return <svg {...props} width={12} height={12} viewBox="0 0 12 12" xmlns="http://www.w3.org/2000/svg" className={className}><path d="M7.5 5.5a1.5 1.5 0 11-3 0 1.5 1.5 0 013 0z" fill={primaryFill} /><path d="M1 3.5C1 2.67 1.67 2 2.5 2h7c.83 0 1.5.67 1.5 1.5v5c0 .83-.67 1.5-1.5 1.5h-7A1.5 1.5 0 011 8.5v-5zM8 9h1.5a.5.5 0 00.5-.5v-5a.5.5 0 00-.5-.5h-7a.5.5 0 00-.5.5v5c0 .28.22.5.5.5H4v-.5a1 1 0 011-1h2a1 1 0 011 1V9z" fill={primaryFill} /></svg>;
}


() => import('./views/base/base.module').then(m => m.BaseModule)


m => m.BaseModule


() => import('./views/buttons/buttons.module').then(m => m.ButtonsModule)


m => m.ButtonsModule


() => import('./views/chartjs/chartjs.module').then(m => m.ChartJSModule)


m => m.ChartJSModule


() => import('./views/dashboard/dashboard.module').then(m => m.DashboardModule)


m => m.DashboardModule


() => import('./views/icons/icons.module').then(m => m.IconsModule)


m => m.IconsModule


() => import('./views/notifications/notifications.module').then(m => m.NotificationsModule)


m => m.NotificationsModule


() => import('./views/manage/manage.module').then(m => m.ManageModule)


m => m.ManageModule


() => import('./views/theme/theme.module').then(m => m.ThemeModule)


m => m.ThemeModule


() => import('./views/widgets/widgets.module').then(m => m.WidgetsModule)


m => m.WidgetsModule


@NgModule({
  imports: [ RouterModule.forRoot(routes, { relativeLinkResolution: 'legacy' }) ],
  exports: [ RouterModule ]
})
export class AppRoutingModule {}


export class AwsS3Component implements Component {
  constructor() {
    this.providers = {
      [AWSS3Bindings.AwsS3Provider.key]: AwsS3Provider,
    };
  }

  providers?: ProviderMap = {};
}


(processCfg: HyperionProcessConfig)=> {
                const type: string = processCfg.type;
                if (this.moduleRegistry.has(type)) {
                    const module: HyperionModule = this.moduleRegistry.get(type);
                    const validator: HyperionValidator = module.getValidator();
                    const err: AsteriaError = validator.validate(processCfg);
                    if (err) {
                        logger.fatal(err.toString());
                        throw ErrorUtil.errorToException(err);
                    } else {
                        const process: StreamProcess = module.buildStreamProcess(processCfg.config);
                        this.PROCESSOR.addProcess(process);
                    }
                } else {
                    const error: AsteriaError = new AsteriaError(
                        AsteriaErrorCode.INVALID_CONFIG,
                        this.getClassName(),
                        `module with reference "${type}" does not exist; use registerModule() to add a module to the hyperion processor`
                    );
                    logger.fatal(error.toString());
                    throw ErrorUtil.errorToException(error);
                }
            }


/**
 * The Hyperion class is the entry point of the Hyperion framework. It provides all functionalities needed
 * for running Asteria processes defined by Plain Old JavaScript objects.
 */
export class Hyperion extends AbstractAsteriaObject {

    /**
     * The session config for this Hyperion instance.
     */
    private readonly CONFIG: HyperionConfig = null;

    /**
     * The reference to the session holded by this Hyperion instance.
     */
    private readonly SESSION: OuranosSession = null;

    /**
     * The reference to the processor used by this Hyperion instance to run Asteria stream processes.
     */
    private readonly PROCESSOR: HyperionProcessor = null;

    /**
     * The module registry associated with this Hyperion instance.
     */
    private moduleRegistry: HyperionModuleRegistry = null;

    /**
     * Create a new Hyperion instance.
     *
     * @param {HyperionConfig} config the config of the session associated with the new Hyperion instance.
     */
    private constructor(config: HyperionConfig) {
        super('com.asteria.hyperion.core::Hyperion');
        this.CONFIG = config;
        this.SESSION = Ouranos.createSession({ name: config.name }) as OuranosSession;
        this.PROCESSOR = new HyperionProcessor(this.SESSION);
    }

    /**
     * Build and return a new Hyperion instance.
     *
     * @param {HyperionConfig} config the description of all Asteria processes managed by this Hyperion
     *                                instance.
     *
     * @returns {Hyperion} a new Hyperion instance.
     */
    public static build(config: HyperionConfig, moduleRegistry: HyperionModuleRegistry = null): Hyperion {
        const processor: Hyperion = new Hyperion(config);
        processor.setModuleRegistry(moduleRegistry);
        return processor;
    }

    /**
     * Return the HyperionModuleRegistry object for this processor.
     *
     * @returns {HyperionModuleRegistry} the HyperionModuleRegistry object for this processor.
     */
    public getModuleRegistry(): HyperionModuleRegistry {
        return this.moduleRegistry;
    }

    /**
     * Set the HyperionModuleRegistry object for this processor.
     *
     * @param {HyperionModuleRegistry} moduleRegistry the new HyperionModuleRegistry object for this
     *                                                processor.
     */
    public setModuleRegistry(moduleRegistry: HyperionModuleRegistry = null): void {
        const logger: AsteriaLogger = (this.SESSION.getContext() as OuranosContext).getLogger();
        if (moduleRegistry) {
            this.moduleRegistry = moduleRegistry;
            logger.info(`new module registry added: ${moduleRegistry.getClassName()}`);
        } else {
            this.initModuleRegistry();
            logger.info('default module registry initialized');
        }
    }

    /**
     * Run all stream processes registered in this Hyperion instance and return the the reference to the
     * last registered stream.
     *
     * @returns {AsteriaStream} the reference to the AsteriaStream objects created by this processor.
     */
    public run(): AsteriaStream {
        this.initProcessor(this.CONFIG);
        return this.PROCESSOR.run();
    }

    /**
     * Stop all stream processes registered in this Hyperion instance.
     */
    public stop(): void {
        // TODO: not implemented yet.
    }

    /**
     * Return the context for this Hyperion instance.
     *
     * @returns {AsteriaContext} the context for this Hyperion instance.
     */
    public getContext(): AsteriaContext {
        return this.SESSION.getContext();
    }

    /**
     * Parse the specified Hyperion config and initialize the processor.
     */
    private initProcessor(config: HyperionConfig): void {
        const processes: Array<HyperionProcessConfig> = config.processes;
        const logger: AsteriaLogger = (this.SESSION.getContext() as OuranosContext).getLogger();
        if (processes && processes.length > 0) {
            config.processes.forEach((processCfg: HyperionProcessConfig)=> {
                const type: string = processCfg.type;
                if (this.moduleRegistry.has(type)) {
                    const module: HyperionModule = this.moduleRegistry.get(type);
                    const validator: HyperionValidator = module.getValidator();
                    const err: AsteriaError = validator.validate(processCfg);
                    if (err) {
                        logger.fatal(err.toString());
                        throw ErrorUtil.errorToException(err);
                    } else {
                        const process: StreamProcess = module.buildStreamProcess(processCfg.config);
                        this.PROCESSOR.addProcess(process);
                    }
                } else {
                    const error: AsteriaError = new AsteriaError(
                        AsteriaErrorCode.INVALID_CONFIG,
                        this.getClassName(),
                        `module with reference "${type}" does not exist; use registerModule() to add a module to the hyperion processor`
                    );
                    logger.fatal(error.toString());
                    throw ErrorUtil.errorToException(error);
                }
            });
        } else {
            const error: AsteriaError = OuranosErrorBuilder.getInstance().build(
                AsteriaErrorCode.MISSING_PARAMETER,
                this.getClassName(),
                'no processes are specified'
            );
            logger.warn(error.toString());
        }
    }

    /**
     * Initialize the module registry with default modules.
     */
    private initModuleRegistry(): void {
        const factory: HyperionModuleRegistryFactory = new HyperionModuleRegistryFactory();
        this.moduleRegistry = factory.create();
    }
}


/**
     * Build and return a new Hyperion instance.
     *
     * @param {HyperionConfig} config the description of all Asteria processes managed by this Hyperion
     *                                instance.
     *
     * @returns {Hyperion} a new Hyperion instance.
     */
public static build(config: HyperionConfig, moduleRegistry: HyperionModuleRegistry = null): Hyperion {
        const processor: Hyperion = new Hyperion(config);
        processor.setModuleRegistry(moduleRegistry);
        return processor;
    }


/**
     * Return the HyperionModuleRegistry object for this processor.
     *
     * @returns {HyperionModuleRegistry} the HyperionModuleRegistry object for this processor.
     */
public getModuleRegistry(): HyperionModuleRegistry {
        return this.moduleRegistry;
    }


/**
     * Set the HyperionModuleRegistry object for this processor.
     *
     * @param {HyperionModuleRegistry} moduleRegistry the new HyperionModuleRegistry object for this
     *                                                processor.
     */
public setModuleRegistry(moduleRegistry: HyperionModuleRegistry = null): void {
        const logger: AsteriaLogger = (this.SESSION.getContext() as OuranosContext).getLogger();
        if (moduleRegistry) {
            this.moduleRegistry = moduleRegistry;
            logger.info(`new module registry added: ${moduleRegistry.getClassName()}`);
        } else {
            this.initModuleRegistry();
            logger.info('default module registry initialized');
        }
    }


/**
     * Run all stream processes registered in this Hyperion instance and return the the reference to the
     * last registered stream.
     *
     * @returns {AsteriaStream} the reference to the AsteriaStream objects created by this processor.
     */
public run(): AsteriaStream {
        this.initProcessor(this.CONFIG);
        return this.PROCESSOR.run();
    }


/**
     * Stop all stream processes registered in this Hyperion instance.
     */
public stop(): void {
        // TODO: not implemented yet.
    }


/**
     * Return the context for this Hyperion instance.
     *
     * @returns {AsteriaContext} the context for this Hyperion instance.
     */
public getContext(): AsteriaContext {
        return this.SESSION.getContext();
    }


/**
     * Parse the specified Hyperion config and initialize the processor.
     */
private initProcessor(config: HyperionConfig): void {
        const processes: Array<HyperionProcessConfig> = config.processes;
        const logger: AsteriaLogger = (this.SESSION.getContext() as OuranosContext).getLogger();
        if (processes && processes.length > 0) {
            config.processes.forEach((processCfg: HyperionProcessConfig)=> {
                const type: string = processCfg.type;
                if (this.moduleRegistry.has(type)) {
                    const module: HyperionModule = this.moduleRegistry.get(type);
                    const validator: HyperionValidator = module.getValidator();
                    const err: AsteriaError = validator.validate(processCfg);
                    if (err) {
                        logger.fatal(err.toString());
                        throw ErrorUtil.errorToException(err);
                    } else {
                        const process: StreamProcess = module.buildStreamProcess(processCfg.config);
                        this.PROCESSOR.addProcess(process);
                    }
                } else {
                    const error: AsteriaError = new AsteriaError(
                        AsteriaErrorCode.INVALID_CONFIG,
                        this.getClassName(),
                        `module with reference "${type}" does not exist; use registerModule() to add a module to the hyperion processor`
                    );
                    logger.fatal(error.toString());
                    throw ErrorUtil.errorToException(error);
                }
            });
        } else {
            const error: AsteriaError = OuranosErrorBuilder.getInstance().build(
                AsteriaErrorCode.MISSING_PARAMETER,
                this.getClassName(),
                'no processes are specified'
            );
            logger.warn(error.toString());
        }
    }


/**
     * Initialize the module registry with default modules.
     */
private initModuleRegistry(): void {
        const factory: HyperionModuleRegistryFactory = new HyperionModuleRegistryFactory();
        this.moduleRegistry = factory.create();
    }


() => {
  const { state, controls } = useContext(ColorGeneratorContext);
  const [activeColor, setActiveColor] = useState('');

  const toggleActiveColor = (color: string) => {
    setActiveColor(activeColor === color ? '' : color);
  };

  return (
    <ul className={styles.selectColors}>
      {Array.from(state.colors).map(([name]) => {
        const { tint, shade } = state.colors.get(name);
        const isOpen = activeColor === name ? true : false;

        return (
          <li
            className={clsx({ [styles.item]: true, [styles.isOpen]: isOpen })}
          >
            <VariableSelector
              name={name}
              isParentOpen={isOpen}
              onClick={()


(color: string) => {
    setActiveColor(activeColor === color ? '' : color);
  }


([name]) => {
        const { tint, shade } = state.colors.get(name);
        const isOpen = activeColor === name ? true : false;

        return (
          <li
            className={clsx({ [styles.item]: true, [styles.isOpen]: isOpen })}
          >
            <VariableSelector
              name={name}
              isParentOpen={isOpen}
              onClick={()


clsx({ [styles.item]: true, [styles.isOpen]: isOpen })


export declare class NgbTimepickerModule {
}


([key, value]) => {
      if (value === null || typeof value === 'undefined') {
        return;
      }

      if (Array.isArray(value)) {
        // eslint-disable-next-line no-param-reassign
        value = value.join(',');
      }

      if (value instanceof Date) {
        // eslint-disable-next-line no-param-reassign
        value = value.toISOString();
      } else if (value !== null && typeof value === 'object') {
        // eslint-disable-next-line no-param-reassign
        value = JSON.stringify(value);
      } else if (value instanceof Function) {
        const part = value();

        return part && parts.push(part);
      }

      parts.push(`${this.encode(key)}=${this.encode(value)}`);

      return;
    }


([, value]) => typeof value !== 'undefined'


(accumulator, [key, value]) => ({ ...accumulator, [key]: value })


(data: T): void => callback(null, data)


(data: T): T => data


(error: Config.Error) => callback(error)


(error: Error) => {
        throw error;
      }


export class BaseClient implements Client {
  private instance: AxiosInstance;

  constructor(protected readonly config: Config) {
    this.instance = axios.create({
      paramsSerializer: this.paramSerializer.bind(this),
      ...config.baseRequestConfig,
      baseURL: config.host,
      headers: this.removeUndefinedProperties({
        [STRICT_GDPR_FLAG]: config.strictGDPR,
        [ATLASSIAN_TOKEN_CHECK_FLAG]: config.noCheckAtlassianToken ? ATLASSIAN_TOKEN_CHECK_NOCHECK_VALUE : undefined,
        ...config.baseRequestConfig?.headers,
      }),
    });

    if (this.config.newErrorHandling === undefined) {
      console.log('Jira.js: Deprecation warning: New error handling mechanism added. Please use `newErrorHandling: true` in config'); // TODO New feature enabling.
    }
  }

  protected paramSerializer(parameters: Record<string, any>): string {
    const parts: string[] = [];

    Object.entries(parameters).forEach(([key, value]) => {
      if (value === null || typeof value === 'undefined') {
        return;
      }

      if (Array.isArray(value)) {
        // eslint-disable-next-line no-param-reassign
        value = value.join(',');
      }

      if (value instanceof Date) {
        // eslint-disable-next-line no-param-reassign
        value = value.toISOString();
      } else if (value !== null && typeof value === 'object') {
        // eslint-disable-next-line no-param-reassign
        value = JSON.stringify(value);
      } else if (value instanceof Function) {
        const part = value();

        return part && parts.push(part);
      }

      parts.push(`${this.encode(key)}=${this.encode(value)}`);

      return;
    });

    return parts.join('&');
  }

  protected encode(value: string) {
    return encodeURIComponent(value)
      .replace(/%3A/gi, ':')
      .replace(/%24/g, '$')
      .replace(/%2C/gi, ',')
      .replace(/%20/g, '+')
      .replace(/%5B/gi, '[')
      .replace(/%5D/gi, ']');
  }

  protected removeUndefinedProperties(obj: Record<string, any>): Record<string, any> {
    return Object.entries(obj)
      .filter(([, value]) => typeof value !== 'undefined')
      .reduce((accumulator, [key, value]) => ({ ...accumulator, [key]: value }), {});
  }

  async sendRequest<T>(requestConfig: RequestConfig, callback: never, telemetryData?: any): Promise<T>;
  async sendRequest<T>(requestConfig: RequestConfig, callback: Callback<T>, telemetryData?: any): Promise<void>;
  async sendRequest<T>(requestConfig: RequestConfig, callback: Callback<T> | never): Promise<void | T> {
    try {
      const modifiedRequestConfig = {
        ...requestConfig,
        headers: this.removeUndefinedProperties({
          Authorization: await AuthenticationService.getAuthenticationToken(this.config.authentication, {
            baseURL: this.config.host,
            url: this.instance.getUri(requestConfig),
            method: requestConfig.method!,
          }),
          ...requestConfig.headers,
        }),
      };

      const response = await this.instance.request<T>(modifiedRequestConfig);

      const callbackResponseHandler = callback && ((data: T): void => callback(null, data));
      const defaultResponseHandler = (data: T): T => data;

      const responseHandler = callbackResponseHandler ?? defaultResponseHandler;

      this.config.middlewares?.onResponse?.(response.data);

      return responseHandler(response.data);
    } catch (e: any) {
      const err = this.config.newErrorHandling && e.isAxiosError ? e.response.data : e;

      const callbackErrorHandler = callback && ((error: Config.Error) => callback(error));
      const defaultErrorHandler = (error: Error) => {
        throw error;
      };

      const errorHandler = callbackErrorHandler ?? defaultErrorHandler;

      this.config.middlewares?.onError?.(err);

      return errorHandler(err);
    }
  }
}


protected paramSerializer(parameters: Record<string, any>): string {
    const parts: string[] = [];

    Object.entries(parameters).forEach(([key, value]) => {
      if (value === null || typeof value === 'undefined') {
        return;
      }

      if (Array.isArray(value)) {
        // eslint-disable-next-line no-param-reassign
        value = value.join(',');
      }

      if (value instanceof Date) {
        // eslint-disable-next-line no-param-reassign
        value = value.toISOString();
      } else if (value !== null && typeof value === 'object') {
        // eslint-disable-next-line no-param-reassign
        value = JSON.stringify(value);
      } else if (value instanceof Function) {
        const part = value();

        return part && parts.push(part);
      }

      parts.push(`${this.encode(key)}=${this.encode(value)}`);

      return;
    });

    return parts.join('&');
  }


protected encode(value: string) {
    return encodeURIComponent(value)
      .replace(/%3A/gi, ':')
      .replace(/%24/g, '$')
      .replace(/%2C/gi, ',')
      .replace(/%20/g, '+')
      .replace(/%5B/gi, '[')
      .replace(/%5D/gi, ']');
  }


protected removeUndefinedProperties(obj: Record<string, any>): Record<string, any> {
    return Object.entries(obj)
      .filter(([, value]) => typeof value !== 'undefined')
      .reduce((accumulator, [key, value]) => ({ ...accumulator, [key]: value }), {});
  }


async sendRequest<T>(requestConfig: RequestConfig, callback: never, telemetryData?: any): Promise<T>;


async sendRequest<T>(requestConfig: RequestConfig, callback: Callback<T>, telemetryData?: any): Promise<void>;


async sendRequest<T>(requestConfig: RequestConfig, callback: Callback<T> | never): Promise<void | T> {
    try {
      const modifiedRequestConfig = {
        ...requestConfig,
        headers: this.removeUndefinedProperties({
          Authorization: await AuthenticationService.getAuthenticationToken(this.config.authentication, {
            baseURL: this.config.host,
            url: this.instance.getUri(requestConfig),
            method: requestConfig.method!,
          }),
          ...requestConfig.headers,
        }),
      };

      const response = await this.instance.request<T>(modifiedRequestConfig);

      const callbackResponseHandler = callback && ((data: T): void => callback(null, data));
      const defaultResponseHandler = (data: T): T => data;

      const responseHandler = callbackResponseHandler ?? defaultResponseHandler;

      this.config.middlewares?.onResponse?.(response.data);

      return responseHandler(response.data);
    } catch (e: any) {
      const err = this.config.newErrorHandling && e.isAxiosError ? e.response.data : e;

      const callbackErrorHandler = callback && ((error: Config.Error) => callback(error));
      const defaultErrorHandler = (error: Error) => {
        throw error;
      };

      const errorHandler = callbackErrorHandler ?? defaultErrorHandler;

      this.config.middlewares?.onError?.(err);

      return errorHandler(err);
    }
  }


export class ColourConfig extends React.Component<IProps, {}> {
  render() {
    return (

            <label className={'form-label'} style={{ lineHeight: '24px' }}


interface IProps {
  updateColourValue: (attribute: string, value: RGBColor) => void
  backgroundColour: RGBColor
}


render() {
    return (

            <label className={'form-label'} style={{ lineHeight: '24px' }}


@NgModule({
  imports: [
    AppModule,
    ServerModule,
    ServerTransferStateModule,
    ModuleMapLoaderModule
  ],
  bootstrap: [AppComponent],
})
export class AppServerModule { }


export default function(
  session: Session,
): LSP.RequestHandler<LSP.TextDocumentPositionParams, LSP.CompletionItem[], never> {
  return support.cancellableHandler(session, async (event, token) => {
    let prefix: null | string = null;
    try {
      prefix = await command.getPrefix(session, event);
    } catch (err) {
      // ignore errors from completing ' .'
    }
    if (null == prefix) return [];
    const colLine = merlin.Position.fromCode(event.position);
    const request = merlin.Query.complete
      .prefix(prefix)
      .at(colLine)
      .with.doc();
    const response = await session.merlin.query(request, token, event.textDocument, Infinity);
    if ("return" !== response.class) return [];
    const entries = response.value.entries || [];
    return entries.map(merlin.Completion.intoCode);
  });
}


async (event, token) => {
    let prefix: null | string = null;
    try {
      prefix = await command.getPrefix(session, event);
    } catch (err) {
      // ignore errors from completing ' .'
    }
    if (null == prefix) return [];
    const colLine = merlin.Position.fromCode(event.position);
    const request = merlin.Query.complete
      .prefix(prefix)
      .at(colLine)
      .with.doc();
    const response = await session.merlin.query(request, token, event.textDocument, Infinity);
    if ("return" !== response.class) return [];
    const entries = response.value.entries || [];
    return entries.map(merlin.Completion.intoCode);
  }


export default class DeleteAchievementRequestService {
  constructor(
    private achievementRequestsRepository: IAchievementRequestsRepository,
  ) {}

  public async execute(id: string): Promise<IExecute> {
    try {
      await this.achievementRequestsRepository.delete(id);

      return {};
    } catch (error) {
      return { error: error.message, shouldLogout: error.shouldLogout };
    }
  }
}


interface IExecute {
  error?: string;
  shouldLogout?: boolean;
}


public async execute(id: string): Promise<IExecute> {
    try {
      await this.achievementRequestsRepository.delete(id);

      return {};
    } catch (error) {
      return { error: error.message, shouldLogout: error.shouldLogout };
    }
  }


/**
 * Gets and sets settings at the "config" level. This handler does not make use of the
 * roomId parameter.
 */
export default class ConfigSettingsHandler extends SettingsHandler {
    public constructor(private featureNames: string[]) {
        super();
    }

    public getValue(settingName: string, roomId: string): any {
        const config = SdkConfig.get() || {};

        if (this.featureNames.includes(settingName)) {
            const labsConfig = config["features"] || {};
            const val = labsConfig[settingName];
            if (isNullOrUndefined(val)) return null; // no definition at this level
            if (val === true || val === false) return val; // new style: mapped as a boolean
            if (val === "enable") return true; // backwards compat
            if (val === "disable") return false; // backwards compat
            if (val === "labs") return null; // backwards compat, no override
            return null; // fallback in the case of invalid input
        }

        // Special case themes
        if (settingName === "theme") {
            return config["default_theme"];
        }

        const settingsConfig = config["settingDefaults"];
        if (!settingsConfig || isNullOrUndefined(settingsConfig[settingName])) return null;
        return settingsConfig[settingName];
    }

    public async setValue(settingName: string, roomId: string, newValue: any): Promise<void> {
        throw new Error("Cannot change settings at the config level");
    }

    public canSetValue(settingName: string, roomId: string): boolean {
        return false;
    }

    public isSupported(): boolean {
        return true; // SdkConfig is always there
    }
}


public getValue(settingName: string, roomId: string): any {
        const config = SdkConfig.get() || {};

        if (this.featureNames.includes(settingName)) {
            const labsConfig = config["features"] || {};
            const val = labsConfig[settingName];
            if (isNullOrUndefined(val)) return null; // no definition at this level
            if (val === true || val === false) return val; // new style: mapped as a boolean
            if (val === "enable") return true; // backwards compat
            if (val === "disable") return false; // backwards compat
            if (val === "labs") return null; // backwards compat, no override
            return null; // fallback in the case of invalid input
        }

        // Special case themes
        if (settingName === "theme") {
            return config["default_theme"];
        }

        const settingsConfig = config["settingDefaults"];
        if (!settingsConfig || isNullOrUndefined(settingsConfig[settingName])) return null;
        return settingsConfig[settingName];
    }


public async setValue(settingName: string, roomId: string, newValue: any): Promise<void> {
        throw new Error("Cannot change settings at the config level");
    }


public canSetValue(settingName: string, roomId: string): boolean {
        return false;
    }


public isSupported(): boolean {
        return true; // SdkConfig is always there
    }


/**
 *
Modifies the self-service WorkSpace management capabilities for your users. For more
 *          information, see Enable Self-Service WorkSpace Management Capabilities for Your Users.

 * @example
 * Use a bare-bones client and the command you need to make an API call.
 * ```javascript
 * import { WorkSpacesClient, ModifySelfservicePermissionsCommand } from "../../client-workspaces/mod.ts";
 * // const { WorkSpacesClient, ModifySelfservicePermissionsCommand } = require("@aws-sdk/client-workspaces"); // CommonJS import
 * const client = new WorkSpacesClient(config);
 * const command = new ModifySelfservicePermissionsCommand(input);
 * const response = await client.send(command);
 * ```
 *
 * @see {@link ModifySelfservicePermissionsCommandInput} for command's `input` shape.
 * @see {@link ModifySelfservicePermissionsCommandOutput} for command's `response` shape.
 * @see {@link WorkSpacesClientResolvedConfig | config} for command's `input` shape.
 *
 */
export class ModifySelfservicePermissionsCommand extends $Command<
  ModifySelfservicePermissionsCommandInput,
  ModifySelfservicePermissionsCommandOutput,
  WorkSpacesClientResolvedConfig
> {
  // Start section: command_properties
  // End section: command_properties

  constructor(readonly input: ModifySelfservicePermissionsCommandInput) {
    // Start section: command_constructor
    super();
    // End section: command_constructor
  }

  /**
   * @internal
   */
  resolveMiddleware(
    clientStack: MiddlewareStack<ServiceInputTypes, ServiceOutputTypes>,
    configuration: WorkSpacesClientResolvedConfig,
    options?: __HttpHandlerOptions
  ): Handler<ModifySelfservicePermissionsCommandInput, ModifySelfservicePermissionsCommandOutput> {
    this.middlewareStack.use(getSerdePlugin(configuration, this.serialize, this.deserialize));

    const stack = clientStack.concat(this.middlewareStack);

    const { logger } = configuration;
    const clientName = "WorkSpacesClient";
    const commandName = "ModifySelfservicePermissionsCommand";
    const handlerExecutionContext: HandlerExecutionContext = {
      logger,
      clientName,
      commandName,
      inputFilterSensitiveLog: ModifySelfservicePermissionsRequest.filterSensitiveLog,
      outputFilterSensitiveLog: ModifySelfservicePermissionsResult.filterSensitiveLog,
    };
    const { requestHandler } = configuration;
    return stack.resolve(
      (request: FinalizeHandlerArguments<any>) =>
        requestHandler.handle(request.request as __HttpRequest, options || {}),
      handlerExecutionContext
    );
  }

  private serialize(input: ModifySelfservicePermissionsCommandInput, context: __SerdeContext): Promise<__HttpRequest> {
    return serializeAws_json1_1ModifySelfservicePermissionsCommand(input, context);
  }

  private deserialize(
    output: __HttpResponse,
    context: __SerdeContext
  ): Promise<ModifySelfservicePermissionsCommandOutput> {
    return deserializeAws_json1_1ModifySelfservicePermissionsCommand(output, context);
  }

  // Start section: command_body_extra
  // End section: command_body_extra
}


export interface ModifySelfservicePermissionsCommandInput extends ModifySelfservicePermissionsRequest {}


export interface ModifySelfservicePermissionsCommandOutput
  extends ModifySelfservicePermissionsResult,
    __MetadataBearer {}


/**
   * @internal
   */
resolveMiddleware(
    clientStack: MiddlewareStack<ServiceInputTypes, ServiceOutputTypes>,
    configuration: WorkSpacesClientResolvedConfig,
    options?: __HttpHandlerOptions
  ): Handler<ModifySelfservicePermissionsCommandInput, ModifySelfservicePermissionsCommandOutput> {
    this.middlewareStack.use(getSerdePlugin(configuration, this.serialize, this.deserialize));

    const stack = clientStack.concat(this.middlewareStack);

    const { logger } = configuration;
    const clientName = "WorkSpacesClient";
    const commandName = "ModifySelfservicePermissionsCommand";
    const handlerExecutionContext: HandlerExecutionContext = {
      logger,
      clientName,
      commandName,
      inputFilterSensitiveLog: ModifySelfservicePermissionsRequest.filterSensitiveLog,
      outputFilterSensitiveLog: ModifySelfservicePermissionsResult.filterSensitiveLog,
    };
    const { requestHandler } = configuration;
    return stack.resolve(
      (request: FinalizeHandlerArguments<any>) =>
        requestHandler.handle(request.request as __HttpRequest, options || {}),
      handlerExecutionContext
    );
  }


private serialize(input: ModifySelfservicePermissionsCommandInput, context: __SerdeContext): Promise<__HttpRequest> {
    return serializeAws_json1_1ModifySelfservicePermissionsCommand(input, context);
  }


private deserialize(
    output: __HttpResponse,
    context: __SerdeContext
  ): Promise<ModifySelfservicePermissionsCommandOutput> {
    return deserializeAws_json1_1ModifySelfservicePermissionsCommand(output, context);
  }


(data:any)=>{this.user=data}


(resp: Response) => {
            this.user= resp.json();
            this.totalRec = this.user.length;
            console.log(this.totalRec);
            console.log(this.page);

            //console.log(JSON.stringify(resp.json()));
        }


(data)=>this.user=data


(data:any)=>{
      data=this.user
      for(let i=0 ;i < this.user.length; ++i){

    this.userphone=this.user[i].phone;
  this.active=this.user[i].active;
  this.category=this.user[i].category;
  this.bodytype=this.user[i].body_type;
  this.willaccept=this.user[i].will_accept_to_work_for_below_category
  this.usernumber=this.user[i].vendor_uuid;
 this.userVehicleNumber=this.user[i].vehicle_number;
    this.userWorkPreference=this.user[i].work_preference;

    // console.log("Finalnumber",this.usernumber);
    csv += [[this.usernumber] ,[this.userphone] ,[this.userVehicleNumber] ,[this.bodytype] ,[this.category] ,[this.active] ,[this.userWorkPreference] ,[this.willaccept] ].join(',');
    csv += '\r\n';
    }
      // console.log("DriverData",data);

    var blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });

    var link = document.createElement("a");
    if (link.download !== undefined) {
      var url = URL.createObjectURL(blob);
      link.setAttribute("href", url);
      link.setAttribute("download", fileName);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }
  }


@Component({
  selector: 'app-reg-online',
  templateUrl: './reg-online.component.html',
  styleUrls: ['./reg-online.component.scss']
})
export class RegOnlineComponent implements OnInit {
userphone:any;
usernumber:any;
userVehicleNumber:any;
userWorkPreference:any;

public user:any;
 public phone:number;
  totalRec : number;
  page: number = 1;

  public popoverTitle: string = 'Deleting Record...';
  public popoverMessage: string = 'Are you sure to Delete ?';
  public confirmClicked: boolean = false;
  public cancelClicked: boolean = false;

  driverusers: any;
  active: any;
  category: any;
  bodytype: any;
  willaccept: any;

  constructor(private httpClient:HttpClient,public matDialog: MatDialog,private serv: EmployeeService, private http:HttpClient,) {
    this.user = new Array<any>();
  }

  ngOnInit() {

    let resp = this.httpClient.get("https://apis.zeigerapp.in/api/driverfour-owner");
    resp.subscribe((data:any)=>{this.user=data})

        this.loadEmployee();
  }
  private loadEmployee() {
    this
        .serv
        .getEmployees()
        .subscribe((resp: Response) => {
            this.user= resp.json();
            this.totalRec = this.user.length;
            console.log(this.totalRec);
            console.log(this.page);

            //console.log(JSON.stringify(resp.json()));
        });
}

refresh() {
  window.location.reload();
}
deleteRow(phone){
   console.log("phone **********",phone);
  let resp=this.httpClient.get('https://apis.zeigerapp.in/api/driverfour-owner/delete?phone='+phone);
  resp.subscribe((data)=>this.user=data);
  // this.phone=this.user['phone']
  for(let i = 0; i < this.user.length; ++i){
      if (this.user[i].phone === phone) {
          this.user.splice(i,1);
      }
  }
}

  openModal(phone,vehicle_number,work_preference,cancelled_cheque_image) {
    const dialogConfig = new MatDialogConfig();
    // The user can't close the dialog by clicking outside its body
    console.log("phone is ",phone)
    console.log("vehicle number is  ",vehicle_number)
    console.log("wprkong is",work_preference)
    dialogConfig.disableClose = true;
    dialogConfig.id = "modal-component";
    dialogConfig.height = "1000px";
    dialogConfig.width = "1100px";
    dialogConfig.data = phone,vehicle_number,work_preference,cancelled_cheque_image;
    // https://material.angular.io/components/dialog/overview
    const modalDialog = this.matDialog.open(DialogDataExampleDialogComponent, dialogConfig);
  }

   download() {
    let fileName = 'FourWheelerOnlineRegistration.csv';
    let columnNames = ["Vendor_uuid","Phone","Vehicle Number","Body Type","Category","Active","Work Preference","Will Accept to work for below category"];
    let header = columnNames.join(',');

    let csv = header;
    csv += '\r\n';

    this.http.get("https://apis.zeigerapp.in/api/driverfour-owner")
    .subscribe((data:any)=>{
      data=this.user
      for(let i=0 ;i < this.user.length; ++i){

    this.userphone=this.user[i].phone;
  this.active=this.user[i].active;
  this.category=this.user[i].category;
  this.bodytype=this.user[i].body_type;
  this.willaccept=this.user[i].will_accept_to_work_for_below_category
  this.usernumber=this.user[i].vendor_uuid;
 this.userVehicleNumber=this.user[i].vehicle_number;
    this.userWorkPreference=this.user[i].work_preference;

    // console.log("Finalnumber",this.usernumber);
    csv += [[this.usernumber] ,[this.userphone] ,[this.userVehicleNumber] ,[this.bodytype] ,[this.category] ,[this.active] ,[this.userWorkPreference] ,[this.willaccept] ].join(',');
    csv += '\r\n';
    }
      // console.log("DriverData",data);

    var blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });

    var link = document.createElement("a");
    if (link.download !== undefined) {
      var url = URL.createObjectURL(blob);
      link.setAttribute("href", url);
      link.setAttribute("download", fileName);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }
  })
  }

}


ngOnInit() {

    let resp = this.httpClient.get("https://apis.zeigerapp.in/api/driverfour-owner");
    resp.subscribe((data:any)=>{this.user=data})

        this.loadEmployee();
  }


private loadEmployee() {
    this
        .serv
        .getEmployees()
        .subscribe((resp: Response) => {
            this.user= resp.json();
            this.totalRec = this.user.length;
            console.log(this.totalRec);
            console.log(this.page);

            //console.log(JSON.stringify(resp.json()));
        });
}


refresh() {
  window.location.reload();
}


deleteRow(phone){
   console.log("phone **********",phone);
  let resp=this.httpClient.get('https://apis.zeigerapp.in/api/driverfour-owner/delete?phone='+phone);
  resp.subscribe((data)=>this.user=data);
  // this.phone=this.user['phone']
  for(let i = 0; i < this.user.length; ++i){
      if (this.user[i].phone === phone) {
          this.user.splice(i,1);
      }
  }
}


openModal(phone,vehicle_number,work_preference,cancelled_cheque_image) {
    const dialogConfig = new MatDialogConfig();
    // The user can't close the dialog by clicking outside its body
    console.log("phone is ",phone)
    console.log("vehicle number is  ",vehicle_number)
    console.log("wprkong is",work_preference)
    dialogConfig.disableClose = true;
    dialogConfig.id = "modal-component";
    dialogConfig.height = "1000px";
    dialogConfig.width = "1100px";
    dialogConfig.data = phone,vehicle_number,work_preference,cancelled_cheque_image;
    // https://material.angular.io/components/dialog/overview
    const modalDialog = this.matDialog.open(DialogDataExampleDialogComponent, dialogConfig);
  }


download() {
    let fileName = 'FourWheelerOnlineRegistration.csv';
    let columnNames = ["Vendor_uuid","Phone","Vehicle Number","Body Type","Category","Active","Work Preference","Will Accept to work for below category"];
    let header = columnNames.join(',');

    let csv = header;
    csv += '\r\n';

    this.http.get("https://apis.zeigerapp.in/api/driverfour-owner")
    .subscribe((data:any)=>{
      data=this.user
      for(let i=0 ;i < this.user.length; ++i){

    this.userphone=this.user[i].phone;
  this.active=this.user[i].active;
  this.category=this.user[i].category;
  this.bodytype=this.user[i].body_type;
  this.willaccept=this.user[i].will_accept_to_work_for_below_category
  this.usernumber=this.user[i].vendor_uuid;
 this.userVehicleNumber=this.user[i].vehicle_number;
    this.userWorkPreference=this.user[i].work_preference;

    // console.log("Finalnumber",this.usernumber);
    csv += [[this.usernumber] ,[this.userphone] ,[this.userVehicleNumber] ,[this.bodytype] ,[this.category] ,[this.active] ,[this.userWorkPreference] ,[this.willaccept] ].join(',');
    csv += '\r\n';
    }
      // console.log("DriverData",data);

    var blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });

    var link = document.createElement("a");
    if (link.download !== undefined) {
      var url = URL.createObjectURL(blob);
      link.setAttribute("href", url);
      link.setAttribute("download", fileName);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }
  })
  }


(res) => {
				return res.json();
		}


res => {}


export default class IvrPrompts extends PathSegment {
	constructor(prv: PathSegment, id?: string, service?) {
		super('ivr-prompts', id, prv, service);
	}

/**
	 * Internal identifier of a message attachment
	 */	content(id?: string) {
		return new Content(this, id);
	}

	/**
	 *
Since 1.0.32 (Release 9.3)

Returns a list of IVR prompts.

Required Permissions

Permission	Description

ReadAccounts	Viewing user account info (including name, business name, address and phone number/account number)

API Group

Medium

	 */
	list(): Promise<IIvrPrompts> {
		return this.getRest().call(this.getEndpoint(false), undefined, {
			body: undefined,
			method: 'get'
		}).then<any>((res) => {
				return res.json();
		});
	}

	/**
	 *
Since 1.0.32 (Release 9.3)

Returns an IVR prompt by ID

Required Permissions

Permission	Description

ReadAccounts	Viewing user account info (including name, business name, address and phone number/account number)

API Group

Medium

	 */
	get(): Promise<PromptInfo> {
		return this.getRest().call(this.getEndpoint(true), undefined, {
			body: undefined,
			method: 'get'
		}).then<any>((res) => {
				return res.json();
		});
	}

	/**
	 *
Since 1.0.32 (Release 9.3)

Deletes an IVR prompt by ID

Required Permissions

Permission	Description

EditAccounts	Viewing user account info (including name, business name, address and phone number/account number)

API Group

Heavy

	 */
	delete(): Promise<void> {
		return this.getRest().call(this.getEndpoint(true), undefined, {
			body: undefined,
			method: 'delete'
		}).then(res => {});
	}

}


/**
	 * Internal identifier of a message attachment
	 */
content(id?: string) {
		return new Content(this, id);
	}


/**
	 *
Since 1.0.32 (Release 9.3)

Returns a list of IVR prompts.

Required Permissions

Permission	Description

ReadAccounts	Viewing user account info (including name, business name, address and phone number/account number)

API Group

Medium

	 */
list(): Promise<IIvrPrompts> {
		return this.getRest().call(this.getEndpoint(false), undefined, {
			body: undefined,
			method: 'get'
		}).then<any>((res) => {
				return res.json();
		});
	}


/**
	 *
Since 1.0.32 (Release 9.3)

Returns an IVR prompt by ID

Required Permissions

Permission	Description

ReadAccounts	Viewing user account info (including name, business name, address and phone number/account number)

API Group

Medium

	 */
get(): Promise<PromptInfo> {
		return this.getRest().call(this.getEndpoint(true), undefined, {
			body: undefined,
			method: 'get'
		}).then<any>((res) => {
				return res.json();
		});
	}


/**
	 *
Since 1.0.32 (Release 9.3)

Deletes an IVR prompt by ID

Required Permissions

Permission	Description

EditAccounts	Viewing user account info (including name, business name, address and phone number/account number)

API Group

Heavy

	 */
delete(): Promise<void> {
		return this.getRest().call(this.getEndpoint(true), undefined, {
			body: undefined,
			method: 'delete'
		}).then(res => {});
	}


function handleDOM(
  doc: Document,
  options: DictConfigs['longman']['options']
): LongmanSearchResult | Promise<LongmanSearchResult> {
  if (doc.querySelector('.dictentry')) {
    return handleDOMLex(doc, options)
  } else if (options.related) {
    return handleDOMRelated(doc)
  }
  return handleNoResult()
}


function handleDOMLex(
  doc: Document,
  options: DictConfigs['longman']['options']
): LongmanSearchResultLex | Promise<LongmanSearchResultLex> {
  const result: LongmanResultLex = {
    type: 'lex',
    bussinessFirst: options.bussinessFirst,
    contemporary: [],
    bussiness: []
  }

  const audio: { uk?: string; us?: string } = {}

  doc
    .querySelectorAll<HTMLSpanElement>('.speaker.exafile')
    .forEach($speaker => {
      const mp3 = $speaker.dataset.srcMp3
      if (mp3) {
        const parent = $speaker.parentElement
        $speaker.replaceWith(getStaticSpeaker(mp3))
        if (parent && parent.classList.contains('EXAMPLE')) {
          parent.classList.add('withSpeaker')
        }
      }
    })

  if (options.wordfams) {
    result.wordfams = getInnerHTML(HOST, doc, '.wordfams')
  }

  const $dictentries = doc.querySelectorAll('.dictentry')
  let currentDict: 'contemporary' | 'bussiness' | '' = ''
  for (let i = 0; i < $dictentries.length; i++) {
    const $entry = $dictentries[i]
    const $intro = $entry.querySelector('.dictionary_intro')
    if ($intro) {
      const dict = $intro.textContent || ''
      if (dict.includes('Contemporary')) {
        currentDict = 'contemporary'
      } else if (dict.includes('Business')) {
        currentDict = 'bussiness'
      } else {
        currentDict = ''
      }
    }

    if (!currentDict) {
      continue
    }

    const entry: LongmanResultEntry = {
      title: {
        HWD: '',
        HYPHENATION: '',
        HOMNUM: ''
      },
      prons: [],
      senses: []
    }

    const $topic = $entry.querySelector<HTMLAnchorElement>('a.topic')
    if ($topic) {
      entry.topic = {
        title: $topic.textContent || '',
        href: getFullLink(HOST, $topic, 'href')
      }
    }

    const $head = $entry.querySelector('.Head')
    if (!$head) {
      continue
    }

    entry.title.HWD = getText($head, '.HWD')
    entry.title.HYPHENATION = getText($head, '.HYPHENATION')
    entry.title.HOMNUM = getText($head, '.HOMNUM')

    entry.phsym = getText($head, '.PronCodes')

    const $level = $head.querySelector('.LEVEL') as HTMLSpanElement
    if ($level) {
      const level = {
        rate: 0,
        title: ''
      }

      level.rate = (($level.textContent || '').match(/●/g) || []).length
      level.title = $level.title

      entry.level = level
    }

    entry.freq = Array.from(
      $head.querySelectorAll<HTMLSpanElement>('.FREQ')
    ).map($el => ({
      title: $el.title,
      rank: $el.textContent || ''
    }))

    entry.pos = getText($head, '.POS')

    $head.querySelectorAll<HTMLSpanElement>('.speaker').forEach($pron => {
      let lang = 'us'
      const title = $pron.title
      if (title.includes('British')) {
        lang = 'uk'
      }
      const pron = $pron.getAttribute('data-src-mp3') || ''

      audio[lang] = pron
      entry.prons.push({ lang, pron })
    })

    entry.senses = Array.from($entry.querySelectorAll('.Sense')).map($sen =>
      getInnerHTML(HOST, $sen)
    )

    if (options.collocations) {
      entry.collocations = getInnerHTML(HOST, $entry, '.ColloBox')
    }

    if (options.grammar) {
      entry.grammar = getInnerHTML(HOST, $entry, '.GramBox')
    }

    if (options.thesaurus) {
      entry.thesaurus = getInnerHTML(HOST, $entry, '.ThesBox')
    }

    if (options.examples) {
      entry.examples = Array.from($entry.querySelectorAll('.exaGroup')).map(
        $exa => getInnerHTML(HOST, $exa)
      )
    }

    result[currentDict].push(entry)
  }

  if (result.contemporary.length <= 0 && result.bussiness.length <= 0) {
    return handleNoResult()
  }

  return { result, audio }
}