import 'dart:math';

import 'package:flutter/material.dart';
import 'package:mwf_app/model/Permission_model.dart';
import 'package:firebase_messaging/firebase_messaging.dart';

import 'package:mwf_app/service/url.dart';
import 'package:mwf_app/service/api.dart';
import 'package:mwf_app/service/pref.dart';
import 'package:mwf_app/service/alert.dart';
import 'package:mwf_app/service/strings.dart';

import 'package:mwf_app/home.dart';
import 'package:mwf_app/set9/login.dart';
import 'package:mwf_app/set9/login_otp.dart';

class LoginModel {
  String userID;
  String employeeID;
  String userName;
  String password;
  String loginStatus;

  LoginModel(
      {this.userID,
      this.employeeID,
      this.userName,
      this.password,
      this.loginStatus});

  static getData() async {
    final response = await AppApi.apiGetRequest(AppUrl.Login_ReadList +
        "?UserID=" +
        AppUrl.UserID +
        "&AuthenKey=" +
        AppUrl.AuthenKey); // เรียกใช้ api
    data.clear(); // เคลียข้อมูลเดิมออกก่อน
    print("test");
    return response;
  }

  static registerGetToken(String username) async {
    String random = (Random.secure().nextInt(9000000)*3).toString();
    String tokenKey = await AppApi.apiGetRequest(AppUrl.CreateSession +
        "?identityId=" + random +
        "&userName=" + username
    ); // เรียกใช้ api
    print(AppUrl.CreateSession +
        "?identityId=" + random +
        "&userName=" + username);
    setPref("string", "AuthenKey", tokenKey);
    AppUrl.AuthenKey = tokenKey;
    print("Token key :: " + tokenKey);
    return tokenKey;
  }

  static checkSession(String key) async {
    print(AppUrl.CheckSession +
        "?authenKey=" + key);
    var response = await AppApi.apiGetRequest(AppUrl.CheckSession +
        "?authenKey=" + key
    ); // เรียกใช้ api

    print("Response :: " + response.toString());
    return response;
  }

  static sendOTP(context, Map json, phonenumber, username, password) async {
    final response =
        await AppApi.postWithMap(AppUrl.SendOTP, json); // เรียกใช้ api

    //if (response.length > 0) {
    if (response['statusCode'] == 200) {
      print("send otp success");
      AppUrl.otpId = response['Id'];
      AppUrl.refCode = response['RefCode'];
      print(AppUrl.refCode);
      setLoading(false);
      Navigator.pushReplacement(
          context,
          MaterialPageRoute(
              builder: (context) => Otp(phonenumber, username, password)));
    } else {
      setLoading(false);
      alertForm(context, "แจ้งเตือน",
          "ส่งรหัส OTP ไม่สำเร็จ หรือ กรอก User และ Password ผิด");
      return false;
    }
  }

  static sendOTPAgain(
      context, Map json, phonenumber, username, password) async {
    final response =
        await AppApi.postWithMap(AppUrl.SendOTP, json); // เรียกใช้ api

    if (response['statusCode'] == 200) {
      print("send otp success");
      AppUrl.otpId = response['Id'];
      AppUrl.refCode = response['RefCode'];
      print(AppUrl.refCode);
      return true;
    } else {
      alertForm(context, "แจ้งเตือน", "ส่งรหัส OTP ไม่สำเร็จ");
      return false;
    }
  }

  static verifyOTP(context, Map json, username, password) async {
    final response =
        await AppApi.postWithMap(AppUrl.VerifyOTP, json); // เรียกใช้ api
    if (response == true) {
      print("verify otp success");
      FirebaseMessaging firebaseMessaging = FirebaseMessaging();
      firebaseMessaging.getToken().then((String token) {
        assert(token != null);
        print("Token : $token");
        Map<String, dynamic> dataLogin = {
          "UserName": username,
          "Password": password,
          "Token": token,
          "OS": AppUrl.os,
          "Version": AppUrl.osVersion,
          "Model": AppUrl.model,
        };
        
        print(dataLogin);
        var res = login(context, dataLogin);
        return res;
      });
    } else {
      return response;
    }
  }

  static login(context, Map json) async {
    final response =
        await AppApi.post2(AppUrl.PEALogin, json); // เรียกใช้ api
    print("----------- login(context,Map json) ----------");
    print(json.toString());
    if (response.length > 0) {
      print("=========== response =============");
      print(response.toString());
      AppUrl.AuthenKey = response['authenKey'];
      AppStrings.userID = response['UserID'];
      AppStrings.empID = response['EmpID'];
      AppUrl.EmpID = response['UserID'];
      AppUrl.EmployeeID = response['EmployeeID'];
      AppUrl.employeeEmpID = response['EmpID'];
      AppUrl.userID = response['UserID'];
      
      print("AppUrl.AuthenKey  : " + AppUrl.AuthenKey);
      print("response['UserID'] : " + response['UserID'].toString());
      print("response['EmpID'] : " + response['EmpID'].toString());
      print("response['EmployeeID'] : " + response['EmployeeID'].toString());

      await setPref("string", "AuthenKey", AppUrl.AuthenKey);
      await setPref("string", "userID", response['UserID']);
      await setPref("string", "empID", response['EmpID']);
      await setPref("string", "EmpID", response['EmpID']);
      await setPref("string", "EmployeeID", response['EmployeeID']);
      await setPref("string", "employeeCode", response['EmployeeID']);

      await setPref("bool", "loginStatus", true);
      await setPref("string", "profileFullName", response['EmployeeName']);
      await setPref("string", "profilePosition", response['employeePosition']);
      await setPref(
          "string", "profilePositionName", response['employeeDepartment']);
      AppStrings.employeeNo = response['EmployeeID'];
      AppStrings.profileFullName = response['EmployeeName'];
      AppStrings.profilePosition = response['employeePosition'];
      AppStrings.profilePositionName = response['employeeDepartment'];
      print("Login Success");

      setLoadingOPT();
      await Permission.setStatus();
      //await NotificationCount.goStream();
      Navigator.pushReplacement(
          context, MaterialPageRoute(builder: (context) => HomePage()));
      return true;
    } else {
      alertForm(context, "แจ้งเตือน", "ชื่อผู้ใช้หรือรหัสผ่านไม่ถูกต้อง");
    }
  }

  static deleteData(
    context,
    String userID,
  ) async {
    Map<String, dynamic> data = {
      "UserID": userID,
      "AuthenKey": AppUrl.AuthenKey
    };
    final response =
        await AppApi.post(AppUrl.Login_Delete, data); // เรียกใช้ api

    if (response['statusCode'] == 200) {
      return true;
    } else {
      return false;
    }
  }

  static updateData(
    context,
    String userID,
    String employeeID,
    String userName,
    String password,
    String loginStatus,
  ) async {
    Map<String, dynamic> data = {
      "UserID": userID,
      "EmployeeID": employeeID,
      "UserName": userName,
      "Password": password,
      "LoginStatus": loginStatus,
      "AuthenKey": AppUrl.AuthenKey
    };
    final response =
        await AppApi.post(AppUrl.Login_Update, data); // เรียกใช้ api

    if (response['statusCode'] == 200) {
      return true;
    } else {
      return false;
    }
  }

  static List<LoginModel> data = []; // ตัวแปรที่จะเรียกใช้งาน

  LoginModel.fromJson(Map<String, dynamic> json) {
    userID = json['UserID'];
    employeeID = json['EmployeeID'];
    userName = json['UserName'];
    password = json['Password'];
    loginStatus = json['LoginStatus'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = Map<String, dynamic>();
    data['UserID'] = this.userID;
    data['EmployeeID'] = this.employeeID;
    data['UserName'] = this.userName;
    data['Password'] = this.password;
    data['LoginStatus'] = this.loginStatus;
    return data;
  }
}
