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.dart';

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

  http.Client client = http.Client();

  //TOKEN
  String? token;

  Future<String> _get(String point, {Map<String, String>? 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.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';
    if(requestBody!=null) {
      log.i(jsonEncode(requestBody));
    }
    final response = await http.post(Uri.https(host, url), body: jsonEncode(requestBody), headers: headers);

    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<Response> dictionaries(String target) async {
    Response result;
    try {
      final Map<String, String> headers = <String, String>{HttpHeaders.authorizationHeader: 'Bearer $token'};
      final String response = await _post(target, header: headers);
      result = Response.fromMapList(json.decode(response), null);
    } catch (e, stack) {
      log.e("dictionaries", e, stack);
      result = Response()..operation=false..list=[];
    }
    return result;
  }
}
