
import 'package:email_validator/email_validator.dart';
import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:top_news_app/services/storage_service.dart';
import '../helper/helper.dart';
import '../localization/localization.dart';
import '../main.dart';
import '../repos/exception_handlers.dart';
import '../repos/repository.dart';

class AuthService{

  Repository? _repository;

  AuthService(){
    _repository = Repository();
  }

  signInWithGoogle(context) async {
  //  begin interactive sign in process
    final GoogleSignInAccount? gUser = await GoogleSignIn().signIn();
    //get auth details from request
    await gUser!.authentication;
    await onlyEmailLogin(context, gUser.email);
  }

  signInWithFacebook(context) async{
    showMessage(getTranslated(context, 'Try another away') ?? 'Try another away');
  }

  onlyEmailLogin(context, email) async{
    var data = {'email': email};
    var response = await _repository?.httpPost('email/login', data);
    var result =  processResponse(response);

    if(result.containsKey('message')){
      showMessage(result['message']);
    }

    //set in preferences
    if(result.containsKey('errors')){
      result['errors'].forEach((key, value){
        showMessage(value[0]);
      });
    }

    //set in preferences
    if(result['result'] == true){
      StorageService().storeAuthSharedPreferences(result);
      Navigator.pushNamed(context, 'main-screen');
    }
  }

  checkAuth() async{
    var result = await _repository?.httpGet('user');
    return processResponse(result);
  }



  login(context,email,password) async {
    if(email.isEmpty){
      showMessage(getTranslated(context, 'Enter the  email') ?? 'Enter the  email');
    } else if(!EmailValidator.validate(email)){
      showMessage(getTranslated(context, 'Enter the valid email') ?? 'Enter the valid email');
    }else if (password.isEmpty){
      showMessage(getTranslated(context, 'Enter the password') ?? 'Enter the password');
    }else{
      //here login code
      var data = {'email': email, 'password': password};
      var response = await _repository?.httpPost('login', data);
      var result =  processResponse(response);

      if(result.containsKey('message')){
        showMessage(result['message']);
      }

      if(result.containsKey('defaultLanguages')){
        Locale locale = await setLocale(result['defaultLanguages']);
        MyApp.setLocale(context, locale);
      }

      //set in preferences
      if(result.containsKey('errors')){
        result['errors'].forEach((key, value){
          showMessage(value[0]);
        });
      }

      //set in preferences
      if(result['result'] == true){
        StorageService().storeAuthSharedPreferences(result);
        Navigator.pushReplacementNamed(context, '/main-screen');
      }
    }

  }

  register(context,email,password,name) async{

    if(email.isEmpty){
      showMessage(getTranslated(context, 'Enter the  email') ?? 'Enter the  email');
    }else if(name.isEmpty){
      showMessage(getTranslated(context, 'Enter the  name') ?? 'Enter the  name');
    }
    else if(!EmailValidator.validate(email)){
      showMessage(getTranslated(context, 'Enter the valid email') ?? 'Enter the valid email');
    }else if (password.isEmpty){
      showMessage(getTranslated(context, 'Enter the password') ?? 'Enter the password');
    }else{
      //register login code
      var data = {'email':email,'password':password,'name':name};
      var response = await _repository?.httpPost('register', data);

      var result =  processResponse(response);

      if(result.containsKey('message')){
        showMessage(result['message']);
      }

      //set in preferences
      if(result.containsKey('errors')){
        result['errors'].forEach((key, value){
          showMessage(value[0]);
        });
      }

      //set in preferences
      if(result['result'] == true){
        onlyEmailLogin(context, result['email']);
      }
    }


  }


  changePassword(String newPassword, String currentPassword) async{
    var data = {'newPassword':newPassword,'currentPassword':currentPassword};
    return await _repository?.httpPost('reset-password',data);
  }

  forgetPasswordOne(String email) async{
    var result = await _repository?.httpGet('1/forget/password/$email');
    return result;
  }

  forgetPasswordTow(String email, String code) async{
    var result = await _repository?.httpGet('2/forget/password/$email/$code');
    return result;
  }

  forgetPasswordThree(String email,String code, String password) async{
    var data = {'email':email,'code':code,'password':password};
    var result = await _repository?.httpPost('3/forget/password', data);
    return result;
  }



  getProfile() async{
    return await _repository?.httpGet('profile');
  }

  logout() async{
    return await _repository?.httpPost('logout',{});
  }
  
  updateProfile(name,bio) async{
    var data = {'name':name,'bio':bio};
    var result = await _repository?.httpPost('update/profile', data);

    return processResponse(result);
  }

  notifications() async{
    var result = await _repository?.httpGet('get-notification');
    return processResponse(result);
  }

  readNotify(id) async {
    var result = await _repository?.httpGetById('read-notification', id.toString());
    return processResponse(result);
  }

}