// Copyright (C) 2022 WYATT GROUP
// Please see the AUTHORS file for details.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

import 'package:http/http.dart';

abstract class RequestUtils {
  static Request _copyNormalRequestWith(
    Request original, {
    String? method,
    Uri? url,
    Map<String, String>? headers,
    int? maxRedirects,
    bool? followRedirects,
    bool? persistentConnection,
    String? body,
  }) {
    final request = Request(method ?? original.method, url ?? original.url)
      ..followRedirects = followRedirects ?? original.followRedirects
      ..headers.addAll(headers ?? original.headers)
      ..maxRedirects = maxRedirects ?? original.maxRedirects
      ..persistentConnection =
          persistentConnection ?? original.persistentConnection
      ..body = body ?? original.body;

    return request;
  }

  static BaseRequest copyRequestWith(
    BaseRequest original, {
    String? method,
    Uri? url,
    Map<String, String>? headers,
    int? maxRedirects,
    bool? followRedirects,
    bool? persistentConnection,
    String? body,
  }) {
    if (original is Request) {
      return _copyNormalRequestWith(
        original,
        method: method,
        url: url,
        headers: headers,
        maxRedirects: maxRedirects,
        followRedirects: followRedirects,
        persistentConnection: persistentConnection,
        body: body,
      );
    } else {
      throw UnimplementedError(
        'Cannot handle requests of type ${original.runtimeType}',
      );
    }
  }

  static Request _copyNormalRequest(Request original) {
    final request = Request(original.method, original.url)
      ..followRedirects = original.followRedirects
      ..headers.addAll(original.headers)
      ..maxRedirects = original.maxRedirects
      ..persistentConnection = original.persistentConnection
      ..body = original.body;

    return request;
  }

  static BaseRequest copyRequest(BaseRequest original) {
    if (original is Request) {
      return _copyNormalRequest(original);
    } else {
      throw UnimplementedError(
        'Cannot handle requests of type ${original.runtimeType}',
      );
    }
  }
}
