import 'dart:convert';
import 'dart:io';

import 'package:satu/core/base/base_service.dart';
import 'package:http/http.dart' as http;
import 'package:satu/core/models/auth/auth_response.dart';
import 'package:satu/core/models/response/response_entity.dart';
import 'package:satu/core/models/flow/analytics/analytics_bean.dart';
import 'package:satu/core/models/flow/sell_request.dart';
import 'package:satu/core/models/flow/sell_response.dart';
import 'package:satu/core/models/flow/sell_return/sell_return_request.dart';

/// The service responsible for networking requests
class ApiService extends BaseService {
  static const host = 'satu.aman.com.kz';
  static const endpoint = '/api/v1';



  //TOKEN
  String? token;

  Future<String> _get(String point,
      {Map<String, String>? header}) async {
    final Map<String, String> headers = <String, String>{
      HttpHeaders.contentTypeHeader: 'application/json',
      HttpHeaders.cacheControlHeader: 'no-cache'
    };
    if (header != null && header.isNotEmpty) {
      headers.addAll(header);
    }
    final String url = '$endpoint$point';
    final response = await http.get(Uri.https(host, url), headers: headers);
    return response.body;
  }

  Future<String> _post(String point,
      {Map<String, dynamic>? requestBody, Map<String, String>? header}) async {
    final Map<String, String> headers = <String, String>{
      HttpHeaders.contentTypeHeader: 'application/json',
      HttpHeaders.cacheControlHeader: 'no-cache',
    };
    if (header != null && header.isNotEmpty) {
      headers.addAll(header);
    }
    final String url = '$endpoint$point';

    final response = await http.post(Uri.https(host, url),
        body: jsonEncode(requestBody), headers: headers);
    if (requestBody != null) {
      // log.i(host);
      // log.i(url);
      // log.i(headers);
      log.i(jsonEncode(requestBody));
      log.i(jsonEncode(response.body));
    }
    return response.body;
  }

  Future<AuthResponse> login(String username, String password) async {
    final Map<String, String> requestBody = <String, String>{
      'username': username,
      'password': password
    };
    AuthResponse result;
    try {
      final String response = await _post('/login', requestBody: requestBody);
      result = AuthResponse.fromMap(json.decode(response));
    } catch (e, stack) {
      log.e('login', e, stack);
      result = AuthResponse()
        ..message = 'Ошибка вызова сервера'
        ..operation = false;
    }
    return result;
  }

  Future<AuthResponse> authorization(String token) async {
    final Map<String, String> requestBody = <String, String>{'token': token};
    AuthResponse result;
    try {
      final String response =
          await _post('/authorization', requestBody: requestBody);
      result = AuthResponse.fromMap(json.decode(response));
    } catch (e, stack) {
      log.e('authorization', e, stack);
      result = AuthResponse()
        ..message = 'Ошибка вызова сервера'
        ..operation = false;
    }
    return result;
  }

  Future<AuthResponse> auth(String token) async {
    final Map<String, String> headers = <String, String>{
      HttpHeaders.authorizationHeader: 'Bearer $token'
    };
    AuthResponse result;
    try {
      final String response = await _post('/auth', header: headers);
      result = AuthResponse.fromMap(json.decode(response));
    } catch (e, stack) {
      log.e('auth', e, stack);
      result = AuthResponse()
        ..message = 'Ошибка вызова сервера'
        ..operation = false;
    }
    return result;
  }

  Future<AuthResponse> logout() async {
    final Map<String, String> headers = <String, String>{
      HttpHeaders.authorizationHeader: 'Bearer $token'
    };
    AuthResponse result;
    try {
      final String response = await _post('/logout', header: headers);
      result = AuthResponse.fromMap(json.decode(response));
    } catch (e, stack) {
      log.e('auth', e, stack);
      result = AuthResponse()
        ..message = 'Ошибка вызова сервера'
        ..operation = false;
    }
    return result;
  }

  Future<ResponseEntity> postRequest(String target,
      {Map<String, dynamic>? requestBody}) async {
    ResponseEntity result;
    try {
      final Map<String, String> headers = <String, String>{
        HttpHeaders.authorizationHeader: 'Bearer $token'
      };

      final String response =
          await _post(target, header: headers, requestBody: requestBody);
      result = ResponseEntity.fromJson(json.decode(response));
    } catch (e, stack) {
      log.e('postRequest', e, stack);
      result = ResponseEntity()..exception = e.toString();
    }
    return result;
  }

  Future<ResponseEntity> dictionarySave(
      String target, Map<String, dynamic>? body) async {
    ResponseEntity response;
    try {
      final Map<String, String> headers = <String, String>{
        HttpHeaders.authorizationHeader: 'Bearer $token'
      };
      final String responseBody =
          await _post(target, header: headers, requestBody: body);
      response = ResponseEntity.fromJson(json.decode(responseBody));
    } catch (e, stack) {
      log.e('dictionarySave', e, stack);
      response = ResponseEntity()..exception = e.toString();
    }
    return response;
  }

  Future<SellResponse> sell(SellRequest request) async {
    SellResponse response;
    try {
      final Map<String, String> headers = <String, String>{
        HttpHeaders.authorizationHeader: 'Bearer $token'
      };
      final String responseBody =
          await _post('/sell', header: headers, requestBody: request.toJson());
      response = SellResponse.fromMap(json.decode(responseBody));
    } catch (e, stack) {
      log.e('dictionaries', e, stack);
      response = SellResponse()
        ..operation = false
        ..message = e.toString();
    }
    return response;
  }

  Future<SellResponse> sellReturn(SellReturnRequest request) async {
    SellResponse response;
    try {
      final Map<String, String> headers = <String, String>{
        HttpHeaders.authorizationHeader: 'Bearer $token'
      };
      final String responseBody = await _post('/sell_return',
          header: headers, requestBody: request.toJson());
      response = SellResponse.fromMap(json.decode(responseBody));
    } catch (e, stack) {
      log.e('sellReturn', e, stack);
      response = SellResponse()
        ..operation = false
        ..message = e.toString();
    }
    return response;
  }

  Future<AnalyticsBean?> getAnalytics() async {
    AnalyticsBean? response;
    try {
      final Map<String, String> headers = <String, String>{
        HttpHeaders.authorizationHeader: 'Bearer $token'
      };
      final String responseBody = await _get('/get_analytics', header: headers);
      response = AnalyticsBean.fromMap(json.decode(responseBody));
    } catch (e, stack) {
      log.e('getAnalytics', e, stack);
    }
    return response;
  }
}
