import 'dart:io';
import 'dart:convert';
import 'package:http/http.dart';
import 'package:school_management_system/components/default_values.dart';

Authorise authoriseFromJson(String str) => Authorise.fromJson(json.decode(str));
String authoriseToJson(Authorise data) => json.encode(data.toJson());

class Authorise {
  DateTime? validUntil;
  String? token;
  String? status;
  String? message;

  Authorise({
    this.validUntil,
    this.token,
    this.status,
    this.message,
  });

  factory Authorise.fromJson(Map<String, dynamic> json) => Authorise(
        validUntil: DateTime.parse(json["validUntil"]),
        token: json["token"],
        status: json["status"],
        message: json["message"],
      );

  Map<String, dynamic> toJson() => {
        "validUntil": validUntil!.toIso8601String(),
        "token": token,
        "status": status,
        "message": message,
      };
}

Future<String> login(String username, String password) async {
  try {
    print("$baseUrl/auth/generateToken");
    final response = await client
        .post(
      Uri.parse("$baseUrl/auth/generateToken"),
      headers: {
        "Content-Type": "application/json",
      },
      body: json.encode({
        'username': username,
        'password': password,
      }),
    )
        .timeout(
      const Duration(seconds: timeout),
      onTimeout: () {
        return Response('', 400);
      },
    );

    if (response.statusCode == 200) {
      var status = authoriseFromJson(response.body)
          .status!; //Authorise.fromJson(json.decode(response.body)).status!;
      loginId = username;
      if (status.isEmpty || status.contains('failed')) {
        return authoriseFromJson(response.body).message!;
      } else {
        setSharedPref('authkey', authoriseFromJson(response.body).token!);
        setSharedPref('tokenValidity',
            authoriseFromJson(response.body).validUntil.toString());
        setSharedPref('isLogin', true);

        header = {
          "Authorization": "Bearer ${authoriseFromJson(response.body).token!}",
          "Content-Type": "application/json",
        };

        return "Successfully Logged In";
      }
    } else if (response.statusCode == 400) {
      return "Cannot Reach Server";
    } else if (response.statusCode == 404) {
      print(response.body);
      return "Not Found";
    } else {
      return "failed";
    }
  } on SocketException {
    return "Can not reach server";
  } on HttpException {
    return "Couldnt find the post";
  } on FormatException {
    return "Bad response format";
  }
}
