// ignore_for_file: public_member_api_docs, sort_constructors_first
// 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_client.dart';
import 'package:wyatt_http_client/src/middlewares/body_to_json_middleware.dart';
import 'package:wyatt_http_client/src/middlewares/simple_logger_middleware.dart';
import 'package:wyatt_http_client/src/middlewares/unsafe_auth_middleware.dart';
import 'package:wyatt_http_client/src/middlewares/uri_prefix_middleware.dart';
import 'package:wyatt_http_client/src/pipeline.dart';
import 'package:wyatt_http_client/src/utils/protocols.dart';

// class RequestMutatorMiddleware implements Middleware {
//   @override
//   Middleware? parent;

//   @override
//   Middleware? child;

//   RequestMutatorMiddleware({
//     this.parent,
//     this.child,
//   });

//   @override
//   BaseRequest onRequest(BaseRequest request) {
//     print('RequestMutator::OnRequest: ${request.method} -> ${request.url}');
//     return child?.onRequest(request) ?? request;
//   }

//   @override
//   BaseResponse onResponse(BaseResponse response) {
//     final res = child?.onResponse(response) ?? response;
//     print(
//       'RequestMutator::OnResponse: ${res.statusCode} -> ${res.contentLength} bytes',
//     );
//     return res;
//   }
// }

// typedef Middleware = Handler Function(Handler innerHandler);

// Middleware createMiddleware({
//   FutureOr<Response?> Function(Request)? requestHandler,
//   FutureOr<Response> Function(Response)? responseHandler,
//   FutureOr<Response> Function(Object error, StackTrace)? errorHandler,
// }) {
//   requestHandler ??= (request) => null;
//   responseHandler ??= (response) => response;

//   FutureOr<Response> Function(Object, StackTrace)? onError;
//   if (errorHandler != null) {
//     onError = (error, stackTrace) {
//       if (error is Exception) throw error;
//       return errorHandler(error, stackTrace);
//     };
//   }

//   return (Handler innerHandler) {
//     return (request) {
//       return Future.sync(() => requestHandler!(request)).then((response) {
//         if (response != null) return response;

//         return Future.sync(() => innerHandler(request))
//             .then((response) => responseHandler!(response), onError: onError);
//       });
//     };
//   };
// }

// extension MiddlewareX on Middleware {
//   Middleware addMiddleware(Middleware other) =>
//       (Handler handler) => this(other(handler));
//   Handler addHandler(Handler handler) => this(handler);
// }

// typedef Handler = FutureOr<Response> Function(Request request);

// final headerMutator = createMiddleware(
//   responseHandler: (response) {
//     print(response.headers);
//     return response;
//   },);

// class Pipeline {
//   const Pipeline();

//   Pipeline addMiddleware(Middleware middleware) =>
//       _Pipeline(middleware, addHandler);

//   Handler addHandler(Handler handler) => handler;

//   Middleware get middleware => addHandler;
// }

// class _Pipeline extends Pipeline {
//   final Middleware _middleware;
//   final Middleware _parent;

//   _Pipeline(this._middleware, this._parent);

//   @override
//   Handler addHandler(Handler handler) => _parent(_middleware(handler));
// }

Future<void> main(List<String> args) async {
  final UnsafeAuthMiddleware auth = UnsafeAuthMiddleware();
  final Pipeline pipeline = Pipeline()
      .addMiddleware(
        UriPrefixMiddleware(
          protocol: Protocols.http,
          authority: 'localhost:80',
        ),
      )
      .addMiddleware(BodyToJsonMiddleware())
      .addMiddleware(
        UnsafeAuthMiddleware(
          username: 'wyatt',
          password: 'motdepasse',
        ),
      )
      .addMiddleware(SimpleLoggerMiddleware());
  // .addMiddleware(
  //   RefreshTokenMiddleware(
  //     authorizationEndpoint: '/api/v1/account/test?action=authorize',
  //     tokenEndpoint: '/api/v1/account/test?action=refresh',
  //     accessTokenParser: (body) => body['access_token']! as String,
  //     refreshTokenParser: (body) => body['refresh_token']! as String,
  //   ),
  // );

  print(pipeline);
  final client = MiddlewareClient(pipeline: pipeline);
  await client.post(
    Uri.parse('/api/v1/account/test'),
    body: <String, String>{
      'email': 'test@test.fr',
    },
  );
  auth
    ..username = 'username'
    ..password = 'password';
  await client.post(
    Uri.parse('/api/v1/account/test'),
    body: <String, String>{
      'email': 'test@test.fr',
    },
  );
}
