import 'dart:developer';
import 'dart:io';

import 'package:auto_route/auto_route.dart';
import 'package:dio/dio.dart';
import 'package:dio/io.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:mnemo_cards/domain/router/app_router.gr.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:http_certificate_pinning/http_certificate_pinning.dart';
import 'package:flutter/foundation.dart';
import 'package:collection/collection.dart';

import '../../di/locator.dart';
import '../../main.dart';

class DioProvider {
  late final Dio _dio;

  DioProvider();

  Dio get dio => _dio;

  Future<DioProvider> init() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    String appVersion = packageInfo.version;

    _dio = Dio()
      ..interceptors.addAll([
        InterceptorsWrapper(onResponse: (response, handler) {
          // if (response.data is List<int>) {
          //   handler.next(response..data = utf8.decode(response.data));
          //   return;
          // }
          handler.next(response);
        }),
        // CertificatePinningInterceptor(allowedSHAFingerprints: [
        //   '28:21:5C:FB:54:4F:4A:DC:F8:5E:4C:FE:44:C8:E0:7B:0B:09:9D:D0:A9:FA:60:1D:3B:03:FF:EC:25:1A:C5:CC',
        // ]),
        InterceptorsWrapper(onError: (exception, handler) {
          if (kDebugMode) {
            log(exception.requestOptions.path ?? '');
            log(exception.toString());
            final snackBar = SnackBar(
              content: Text(
                  '${exception.requestOptions.path}\n${exception.requestOptions.data}\n${exception.toString()}'),
            );
            ScaffoldMessenger.of(scaffoldKey.currentContext!)
                .showSnackBar(snackBar);
          }
          // if (exception.response?.statusCode == 401 &&
          //     !locator.userManager.hasUser) {
          //   try {
          //     if (!AutoRouter.of(scaffoldKey.currentContext!)
          //         .isRouteActive(ProfilePage.name)) {
          //       AutoRouter.of(scaffoldKey.currentContext!).push(
          //         PageRouteInfo(ProfilePage.name),
          //       );
          //     }
          //   } catch (e) {}
          // }
          handler.next(exception);
        }),
        InterceptorsWrapper(onRequest: (request, handler) {
          request.headers = {...request.headers, 'app_version': appVersion};
          handler.next(request);
        })
      ]);

    // final sslCert = await rootBundle.load('assets/ca.crt');
    // final clientCert = await rootBundle.load('assets/client.crt');
    // final sslKey = await rootBundle.load('assets/client.key');
    SecurityContext securityContext = SecurityContext(withTrustedRoots: true);
    // securityContext.setTrustedCertificatesBytes(
    //   sslCert.buffer.asInt8List(),
    // );
    // securityContext.setTrustedCertificatesBytes(
    //   clientCert.buffer.asInt8List(),
    // );
    // securityContext.usePrivateKeyBytes(sslKey.buffer.asInt8List());

    (_dio.httpClientAdapter as IOHttpClientAdapter).createHttpClient = () {
      HttpClient httpClient = HttpClient(context: securityContext)
        ..badCertificateCallback =
            (X509Certificate cert, String host, int port) {
          print(cert.issuer);
          print('$host $port');
          final now = DateTime.now();
          final valid =
              cert.startValidity.isBefore(now) && cert.endValidity.isAfter(now);
          return valid &&
              const DeepCollectionEquality().equals(
                cert.sha1,
                _cert,
              );
          return true;
        };
      return httpClient;
    };
    return this;
  }

  static final _cert =
      '0A:82:77:1E:97:98:05:76:FC:ED:76:89:87:12:E8:9E:92:14:94:D3'
          .split(':')
          .map((v) => int.parse(v, radix: 16))
          .toList();
}
