// 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:wyatt_http_client/src/middleware.dart';
import 'package:wyatt_http_client/src/models/middleware_context.dart';
import 'package:wyatt_http_client/src/models/middleware_request.dart';
import 'package:wyatt_http_client/src/models/middleware_response.dart';
import 'package:wyatt_http_client/src/utils/digest_auth.dart';
import 'package:wyatt_http_client/src/utils/header_keys.dart';
import 'package:wyatt_http_client/src/utils/http_status.dart';

class DigestAuthMiddleware
    with OnRequestMiddleware, OnResponseMiddleware
    implements Middleware {

  DigestAuthMiddleware({
    required this.username,
    required this.password,
    this.authenticationHeader = HeaderKeys.authorization,
    this.wwwAuthenticateHeader = HeaderKeys.wwwAuthenticate,
    this.unauthorized = HttpStatus.unauthorized,
  }) : _digestAuth = DigestAuth(username, password);
  final String username;
  final String password;
  final DigestAuth _digestAuth;
  final String authenticationHeader;
  final String wwwAuthenticateHeader;
  final HttpStatus unauthorized;

  @override
  String getName() => 'DigestAuth';

  @override
  Future<MiddlewareRequest> onRequest(
    MiddlewareContext context,
    MiddlewareRequest request,
  ) async {
    print(
      '${getName()}::OnRequest\n'
      '>> Digest ready: ${_digestAuth.isReady()}',
    );
    if (_digestAuth.isReady()) {
      final mutation = {
        authenticationHeader: _digestAuth.getAuthString(
          request.method,
          request.url,
        ),
      };
      final Map<String, String> headers = request.headers..addAll(mutation);
      request
          .modifyRequest(request.unfreezedRequest.copyWith(headers: headers));
    }
    return request;
  }

  @override
  Future<MiddlewareResponse> onResponse(
    MiddlewareContext context,
    MiddlewareResponse response,
  ) async {
    if (response.status == unauthorized) {
      final authInfo =
          response.headers[HeaderKeys.wwwAuthenticate.toLowerCase()];
      _digestAuth.initFromAuthenticateHeader(authInfo);

      final MiddlewareRequest? newRequest = context.lastRequest?.copyWith();

      if (newRequest != null) {
        final newResponse = await context.client.send(newRequest.request);
        return MiddlewareResponse(httpResponse: newResponse);
      }
    }
    print(
      '${getName()}::OnResponse\n'
      '>> Digest ready: ${_digestAuth.isReady()}',
    );
    return response;
  }
}
