import 'dart:async';
import 'dart:developer';

import 'package:feelverapp/model/Login/login_model.dart';


import 'package:feelverapp/service/Loading.dart';

import 'package:feelverapp/service/api.dart';
import 'package:feelverapp/service/base_presenter.dart';
import 'package:feelverapp/ui/home/home.dart';
import 'package:feelverapp/ui/login/login.dart';
import 'package:feelverapp/util/Accout_util.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:rflutter_alert/rflutter_alert.dart';



class LoginPresenter extends BasePresenter<LoginPage> {
  Api _api;
 Timer _timer;
  final formKey = GlobalKey<FormState>();
  TextEditingController emailCtrl = TextEditingController();
  TextEditingController passCtrl = TextEditingController();
   TextEditingController phonenumberCtrl = TextEditingController();





  LoginPresenter(State<LoginPage> state) : super(state);






/////email Login/////////

letCheckData() async {
      // if(!verifyPhoneState){
      //     throw(allTranslations.text(key: 'please_verify_phone'));
      //   }
     
       try {
        if (emailCtrl.text.isEmpty ) throw ('กรุณากรอก\nอีเมล์');
           else if (passCtrl.text.isEmpty ) throw('กรุณากรอก\nรหัสผ่าน');

            Pattern pattern =
           r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[a-zA-Z0-9]+\.[a-zA-Z]+";
        RegExp regex = new RegExp(pattern);
          if (!regex.hasMatch(emailCtrl.text))
            throw  ('รูปแบบอีเมล์\nไม่ถูกต้อง');

else {
          await letSignIn();
        }
      } catch (e) {
          Alert(
        style: AlertStyle(
      animationType: AnimationType.fromTop,
      isCloseButton: false,
     
      ),
        context: state.context,
        title: '$e',
        content: Icon(Icons.warning,color: Colors.orange,size: 80,),
        buttons: [
          DialogButton(
            color:  Color.fromRGBO(106, 179, 170, 1),
            onPressed: () => Navigator.pop(state.context),
            child: Text(
              "ตกลง",
              style: TextStyle(color: Colors.white, fontSize: 20),
            ),
          )
        ]).show();
      }

  } 

  letSignIn() async {
 LoadingView(state.context).show();
    _api = Api<LoginModel>();

    var res = await _api.login({
      "access_type":"mobile",
      "access_status":"customer",
      "email": emailCtrl.text,
      'password':passCtrl.text
    });
 LoadingView(state.context).hide();


    if (res.fail == null) {
    
      Alert(
        style: AlertStyle(
      animationType: AnimationType.fromTop,
      isCloseButton: false,
     
      ),
        context: state.context,
        title: "เข้าสู่ระบบสำเร็จ",
        content: Icon(Icons.check_circle,color: Color.fromRGBO(106, 179, 170, 1),size: 80,),
        buttons: [
          DialogButton(
            color:  Color.fromRGBO(106, 179, 170, 1),
            onPressed: () =>  
Navigator.pushReplacement(state.context, CupertinoPageRoute(builder: (_) => HomePage())),
            child: Text(
              "ตกลง",
              style: TextStyle(color: Colors.white, fontSize: 20),
            ),
          )
        ]).show();
      LoginModel model = res.success;
         await AccountUtil.saveToken(model.token);
         print( await AccountUtil.getToken());
         // print(AccountUtil.getToken().toString());
     // print("Username ="+"${model.user}");
     
  
          } else {
   Alert(
        style: AlertStyle(
      animationType: AnimationType.fromTop,
      isCloseButton: false,
     
      ),
        context: state.context,
        title: "อีเมล์หรือรหัสผ่าน\nไม่ถูกต้อง",
        content: Icon(Icons.warning,color: Colors.orange,size: 80,),
        buttons: [
          DialogButton(
            color:  Color.fromRGBO(106, 179, 170, 1),
            onPressed: () => Navigator.pop(state.context),
            child: Text(
              "ลองอีกครั้ง",
              style: TextStyle(color: Colors.white, fontSize: 20),
            ),
          )
        ]).show();
    }
  }

















///////phone log in////////////////




  letSignIn_phone() async {
 LoadingView(state.context).show();
    _api = Api<LoginModel>();

    var res = await _api.login({
      "access_type":"mobile",
      "access_status":"customer",
      "email": phonenumberCtrl.text,
      'password':passCtrl.text
    });
 LoadingView(state.context).hide();


    if (res.fail == null) {
      Alert(
        style: AlertStyle(
      animationType: AnimationType.fromTop,
      isCloseButton: false,
     
      ),
        context: state.context,
        title: "เข้าสู่ระบบสำเร็จ",
        content: Icon(Icons.check_circle,color: Color.fromRGBO(106, 179, 170, 1),size: 80,),
        buttons: [
          DialogButton(
            color:  Color.fromRGBO(106, 179, 170, 1),
            onPressed: () =>  
Navigator.pushReplacement(state.context, CupertinoPageRoute(builder: (_) => HomePage())),
            child: Text(
              "ตกลง",
              style: TextStyle(color: Colors.white, fontSize: 20),
            ),
          )
        ]).show();
      LoginModel model = res.success;
     // print("Username ="+"${model.user}");
     
      print("Token ="+"${model.token}");
          } else {
   Alert(
        style: AlertStyle(
      animationType: AnimationType.fromTop,
      isCloseButton: false,
     
      ),
        context: state.context,
        title: "เบอร์โทรศัพท์หรือรหัสผ่าน\nไม่ถูกต้อง",
        content: Icon(Icons.warning,color: Colors.orange,size: 80,),
        buttons: [
          DialogButton(
            color:  Color.fromRGBO(106, 179, 170, 1),
            onPressed: () => Navigator.pop(state.context),
            child: Text(
              "ลองอีกครั้ง",
              style: TextStyle(color: Colors.white, fontSize: 20),
            ),
          )
        ]).show();
    }
  }
     letCheckData_phone() async {
      // if(!verifyPhoneState){
      //     throw(allTranslations.text(key: 'please_verify_phone'));
      //   }
     
       try {
        if (phonenumberCtrl.text.isEmpty ) throw ('กรุณากรอก\nเบอร์โทรศัพท์มือถือ');
           else if (passCtrl.text.isEmpty ) throw('กรุณากรอก\nรหัสผ่าน');


             Pattern pattern =
           r'(^(?:[+0]9)?[0-9]{10,12}$)';
        RegExp regex = new RegExp(pattern);
        if (!regex.hasMatch(phonenumberCtrl.text))
            throw  ('รูปแบบเบอร์โทรศัพท์\nไม่ถูกต้อง');
else {
          await letSignIn_phone();
        }
      } catch (e) {
          Alert(
        style: AlertStyle(
      animationType: AnimationType.fromTop,
      isCloseButton: false,
     
      ),
        context: state.context,
        title: '$e',
        content: Icon(Icons.warning,color: Colors.orange,size: 80,),
        buttons: [
          DialogButton(
            color:  Color.fromRGBO(106, 179, 170, 1),
            onPressed: () => Navigator.pop(state.context),
            child: Text(
              "ตกลง",
              style: TextStyle(color: Colors.white, fontSize: 20),
            ),
          )
        ]).show();
      }

  } 


 
  


  // facebookLogin() async {
  //   try {
  //     await _facebookLogin.logIn(['email']).then((result) async {
  //       var fbData = await Api().getFacebookInfo(result.accessToken.token);
  //       print(fbData);

  //       await _letSocialSignIn(result.accessToken.userId, 'facebook')
  //           .then((value) {
  //         if (value) {
  //           Navigator.popUntil(state.context, (route) => route.isFirst);
  //           Navigator.pushReplacement(state.context, CupertinoPageRoute(builder: (_) => 
              
  //     NavigatorPage(),
  //           ));
  //         } else {
  //           Navigator.push(
  //               state.context,
  //               CupertinoPageRoute(
  //                   builder: (_) => SignUpEmail(
  //                         socialType: SocialType.facebook,
  //                         socialData: new RegisterSocialDataModel(
  //                           socialId: result.accessToken.userId,
  //                           token: result.accessToken.token,
  //                           email: fbData['email'],
  //                           firstName: fbData['first_name'],
  //                           lastName: fbData['last_name'],
  //                         ),
  //                       )));
  //         }
  //       });
  //     });
  //   } catch (e) {
  //     print(e);
  //   }
  // }

 
}
