// Copyright 2018 The Outline Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import * as jsonic from 'jsonic';

import {ManualServerConfig} from '../model/server';

// Parses a server management URL (generated by the server install script) leniently.
// TODO: ignore case of key names
// TODO: check value types
export function parseManualServerConfig(userInput: string): ManualServerConfig {
  // Remove anything before and after the first and last braces, if found.
  const indexOfFirstBrace = userInput.indexOf('{');
  if (indexOfFirstBrace >= 0) {
    userInput = userInput.substring(indexOfFirstBrace);
  }
  const indexOfLastBrace = userInput.lastIndexOf('}');
  if (indexOfLastBrace >= 0) {
    userInput = userInput.substring(0, indexOfLastBrace + 1);
  }

  // Strip whitespace.
  userInput = userInput.replace(/\s+/g, '');

  const config = jsonic(userInput) as ManualServerConfig;

  if (!config.apiUrl) {
    throw new Error('no apiUrl field');
  }

  return config;
}
