import 'dart:convert';
import 'dart:math';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
import 'package:get_secure_storage/get_secure_storage.dart';
import 'package:service/helpers/const.dart';
import 'package:service/helpers/encrypt.dart';

class Helper {
  static double getWidth(BuildContext context) {
    return MediaQuery.of(context).size.width;
  }

  static double getHeight(BuildContext context) {
    return MediaQuery.of(context).size.height;
  }

  final _storage = GetSecureStorage();
  Future<void> writeData(String key, String value) async {
    await _storage.write(key, value);
  }

  Future<String?> readData(String key) async {
    return _storage.read(key);
  }

  Future<void> deleteData(String key) async {
    await _storage.remove(key);
  }

  Future<void> deleteAllData() async {
    await _storage.erase();
  }

  Future<void> deleteAllDataExceptPlayer() async {
    dynamic playerLogin = await readData('playerlogin');
    dynamic url = await readData('mainUrl');
    deleteAllData();
    writeData('playerlogin', playerLogin);
    writeData('mainUrl', url);
  }

  Future<String> generateRandom() async {
    final Random random = Random.secure();
    const String chars =
        'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';

    return String.fromCharCodes(Iterable.generate(
        12, (_) => chars.codeUnitAt(random.nextInt(chars.length))));
  }

  Future<dynamic> doLogin(username, password) async {
    final randomParam = await generateRandom();
    final url = Uri.parse('$mainServer?a=$randomParam');
    final requestBody = {
      'avertec_action': DataEncryptor().encryptData('doLogin'),
      'a': username,
      'b': password
    };

    final response = await http.post(url, body: requestBody);
    if (response.statusCode == 200) {
      return json.decode(response.body) as Map<String, dynamic>;
    } else {
      throw Exception(
          'Failed to make request. Error code: ${response.statusCode}');
    }
  }

  Future<dynamic> getTotalRentalRecord() async {
    final randomParam = await generateRandom();
    final url = Uri.parse('$mainServer?a=$randomParam');
    final regionId = await readData('regionId');
    final read = await readData('read');
    final requestBody = {
      'avertec_action': DataEncryptor().encryptData('getTotalRecord'),
      'a': regionId,
      'b': read.toString()
    };

    final response = await http.post(url, body: requestBody);
    if (response.statusCode == 200) {
      return json.decode(response.body) as Map<String, dynamic>;
    } else {
      throw Exception(
          'Failed to make request. Error code: ${response.statusCode}');
    }
  }

  Future<dynamic> getAllRentalList() async {
    final randomParam = await generateRandom();
    final url = Uri.parse('$mainServer?a=$randomParam');
    final regionId = await readData('regionId');
    final read = await readData('read');
    final requestBody = {
      'avertec_action':
          DataEncryptor().encryptData('getAllRentalContractByCustomer'),
      'a': regionId,
      'b': read.toString()
    };

    final response = await http.post(url, body: requestBody);
    if (response.statusCode == 200) {
      return json.decode(response.body) as Map<String, dynamic>;
    } else {
      throw Exception(
          'Failed to make request. Error code: ${response.statusCode}');
    }
  }

  Future<dynamic> getAllRentalByCustomer() async {
    final randomParam = await generateRandom();
    final url = Uri.parse('$mainServer?a=$randomParam');
    final regionId = await readData('regionId');
    final cid = await readData('userId');
    final read = await readData('read');
    final requestBody = {
      'avertec_action': DataEncryptor().encryptData('getCustomerRental'),
      'a': cid.toString(),
      'b': read.toString(),
      'c': regionId,
    };

    final response = await http.post(url, body: requestBody);
    if (response.statusCode == 200) {
      return json.decode(response.body) as Map<String, dynamic>;
    } else {
      throw Exception(
          'Failed to make request. Error code: ${response.statusCode}');
    }
  }

  Future<dynamic> getRentalDetail(rentalId) async {
    final randomParam = await generateRandom();
    final url = Uri.parse('$mainServer?a=$randomParam');
    final read = await readData('read');
    final requestBody = {
      'avertec_action': DataEncryptor().encryptData('getCustomerRentalDetail'),
      'a': rentalId.toString(),
      'b': read.toString(),
    };

    final response = await http.post(url, body: requestBody);
    if (response.statusCode == 200) {
      return json.decode(response.body) as Map<String, dynamic>;
    } else {
      throw Exception(
          'Failed to make request. Error code: ${response.statusCode}');
    }
  }

  Future<dynamic> updateRentalDetail(data) async {
    final randomParam = await generateRandom();
    final url = Uri.parse('$mainServer?a=$randomParam');
    final read = await readData('read');
    final requestBody = {
      'avertec_action': DataEncryptor().encryptData('getCustomerRentalDetail'),
      'a': data.toString(),
      'b': read.toString(),
    };

    final response = await http.post(url, body: requestBody);
    if (response.statusCode == 200) {
      return json.decode(response.body) as Map<String, dynamic>;
    } else {
      throw Exception(
          'Failed to make request. Error code: ${response.statusCode}');
    }
  }

  Future<dynamic> getNewRental() async {
    final randomParam = await generateRandom();
    final url = Uri.parse('$mainServer?a=$randomParam');
    final read = await readData('read');
    final regionId = await readData('regionId');
    final requestBody = {
      'avertec_action':
          DataEncryptor().encryptData('getNewRentalContractByCustomer'),
      'a': regionId.toString(),
      'b': read.toString(),
    };

    final response = await http.post(url, body: requestBody);
    if (response.statusCode == 200) {
      return json.decode(response.body) as Map<String, dynamic>;
    } else {
      throw Exception(
          'Failed to make request. Error code: ${response.statusCode}');
    }
  }
}
