execute method

dynamic execute(
  1. String _method,
  2. SellonMethod sellonMethod,
  3. Parameter _parameter,
  4. OnSuccessListener _onSuccessListener, {
  5. bool? isShowMessage,
  6. bool? encrytion,
})

Implementation

execute(String _method, SellonMethod sellonMethod, Parameter _parameter,
    OnSuccessListener _onSuccessListener,
    {
    //   OnSuccessListListener? onSuccessListListener,
    // OnSuccessStringListener? onSuccessStringListener,
    bool? isShowMessage,
    bool? encrytion
    }) async {
  int _errCode = 0;
  String _errMessage = '';

  if (encrytion == null){
    encrytion = false;
  }

  // Methods.listApiEncryption.forEach((element) {
  //   if(element == _method){
  //     encrytion = true;
  //   }
  // });

  // if (_method == "community_like/baruv3/"){
  //   encrytion = true;
  // }


  this._onSuccessListener = _onSuccessListener;

  // if (onSuccessListListener != null) {
  //   this._onSuccessListListener = onSuccessListListener;
  // }
  // if (onSuccessStringListener != null) {
  //   this._onSuccessStringListener = onSuccessStringListener;
  // }

  if (this._onErrorListener == null) {
    this._onErrorListener = (error) {
      if (isShowMessage == null) {
        if (error.errCode != 1040 || error.errCode != 799) {
          if (error.errMessage != "") {
            // Ui(context).errorAlert(title: 'Oops', message: error.errMessage!);
          }
        }

        if (error.errCode == 799){
          // SellonRouter.makeFirst(context, MaintanceScreen(isErrorApi: true,domainbefore: Config.domainMain == "sellon.net" ? "sellon.store" : "sellon.net" ,key: UniqueKey(),));
        }
      }
    };
  }

  if (this._onExceptionListener == null) {
    this._onExceptionListener = (ex) {
      // String msg = ex.toString().replaceAll("Exception: ", "");
      // Ui(context).errorAlert(title: 'Oops', message: "No Internet");
    };
  }

  if (_errCode == 0) {
    if (_method.isEmpty) {
      _errCode++;
      _errMessage = 'Method empty';
    }
  }

  if (_errCode == 0) {
    // if (_parameter == null) {
    //   _errCode++;
    //   _errMessage = 'Parameter empty';
    // }
  }

  if (_errCode == 0) {
    if (this._paginator != null) {
      this
          ._paginator!
          .setOnSuccessPaginator(this._onSuccessListener)
          .setup(_method, sellonMethod, _parameter);
    }
  }

  // var index = 0;

  // _parameter.data.forEach((key, val) {
  //   index++;
  // });
  try {
    if (_errCode == 0) {
      final result = await InternetAddress.lookup('google.com');
      // print("curret timezone asss ${result}");

      if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
        Config.AppVersion == VersionApps.indonesia
            ? _parameter.set('nation_code', "62")
            : _parameter.set('nation_code', "65");


        if (Config.apiKey != null) {
          _parameter.set('apikey', Config.apiKey!);
        }
        // if (_method != Methods.pelangganLogin || _method != "bank/list/"
        //     // || _method != "pelanggan/check_version_mobile_app/"
        //     ) {
        //   if (apisess != null) {
        //     _parameter.set('apisess', apisess);
        //   }
        // }
        if (Config.apiSes != null) {
          _parameter.set('apisess', Config.apiSes!);
        }

        if (_method != 'language/change/' ||
            _method != "language/user/") {
          if (Config.bahasa == Bahasa.indonesia) {
            _parameter.set("language_id", "2");
          } else {
            _parameter.set("language_id", "1");
          }
        }
        final String currentTimeZone =
        await FlutterTimezone.getLocalTimezone();
        if (_method != "bank/list/") {
          _parameter.set("timezone", currentTimeZone);
        }
        executeFuture(
            _method,
            // Config.postMethod != null && Config.postMethod! ? SellonMethod.post :
            sellonMethod, _parameter, _onSuccessListener,encryption: encrytion)
            .then((body) async {
          if (Config.openApi) {
            print("bodyyyy ${_method} ${body}");
          }
          if (body == null) {
            // _handleResponseError('799', "Sorry We will back soon", _method, _parameter, _onSuccessListener);
            this._onErrorListener!(new Error(this, 799, body!));
          } else {
            if (body == "Please wait for a while") {
              this._onErrorListener!(new Error(this, 99999, ''));
              _handleResponseError(
                  null, null, _method, _parameter, _onSuccessListener);
            } else {
              if(Config.openApi){
                print("error ${body}");
              }

              var item = jsonDecode(body);

              if(item is Map){
                int code = 200;
                if (item['status'] is String) {
                  code = int.parse(item['status']);
                } else if (item['status'] is int) {
                  code = item['status'];
                }
                if (code == 200) {
                  // if (_method == Methods.pelangganLogin) {
                  //   if (Config.AppVersion == VersionApps.indonesia) {
                  //     getLanguageUser();
                  //   }
                  // }
                  if (item['data'] is List) {
                    Success success = new Success(this, item);
                    this._onSuccessListener(success);
                  } else if (item['data'] is String) {
                    Success success = new Success(this, item);
                    this._onSuccessListener(success);
                  } else {
                    Success success = new Success(this, item);
                    this._onSuccessListener(success);
                  }
                }
                else {
                  if (code == 400) {
                    await ApiSellon.createDefaultParams((parameter) async {
                      parameter.set('username', 'mobile');
                      parameter.set('password',
                          'a4786851f5261822f0f57182ee2dc656b57687c8a105c1b697c280ef48aee7e8');
                      Config.AppVersion == VersionApps.indonesia
                          ? parameter.set('nation_code', '62')
                          : parameter.set('nation_code', '65');
                      await ApiSellon(context).execute(
                          'apikey/auth/', SellonMethod.post, parameter,
                              (response) async {
                            String apikey = response.data()['data']['apikey_plain'];

                            var bytes =
                            utf8.encode(apikey); // data being hashed
                            var sha256c = sha256.convert(bytes);
                            // Preferences.setApiKey(sha256c.toString());
                            Config.apiKey = sha256c.toString();
                            await ApiSellon.createDefaultParams(
                                    (parameter) async {
                                  // up
                                  parameter = _parameter;
                                  _parameter.set('apikey', sha256c.toString());
                                  Config.AppVersion == VersionApps.indonesia
                                      ? _parameter.set('nation_code', "62")
                                      : _parameter.set('nation_code', 65);

                                  // if(_method == "pelanggan/check_version_mobile_app/"){
                                  //   _parameter.set('nation_code', "65");
                                  // }

                                  _parameter.set('apisess', sha256c.toString());
                                  // _parameter.set(
                                  //     "timezone", Helper().dateNowChange());

                                  ApiSellon api2 = ApiSellon(_context!);
                                  api2.setErrorListener((error) {
                                    this._onErrorListener!(new Error(this,
                                        error.errCode, error.errMessage));
                                  });
                                  await api2.execute(
                                      _method, sellonMethod, _parameter,
                                          (response) {
                                        int status = response.data()["status"];
                                        if (status == 200) {
                                          Success success = response;
                                          this._onSuccessListener(success);
                                        }
                                      },
                                      isShowMessage: _method.contains(
                                          "pelanggan/login_sosmedv3")
                                          ? false
                                          : true);
                                  // await ApiSellon(_context).execute(
                                  //     _method, sellonMethod, _parameter,
                                  //     (response) {
                                  //   int status = response.data()["status"];
                                  //   if (status == 200) {
                                  //     Success success = response;
                                  //     this._onSuccessListener(success);
                                  //   }
                                  // });
                                  // }

                                  // last
                                });
                          });
                    });
                  }
                  else if (code == 401 &&
                      item['message']
                          .toString()
                          .toLowerCase()
                          .contains("missing or invalid api session") ||
                      item['message']
                          .toString()
                          .toLowerCase()
                          .contains("sesi api tidak ada")) {
                    // Preferences.getId().then((value) async {
                    //   if (value != null || value != '' || value != 'null') {
                    //     // Helper().modalSellOn(context,
                    //     //     alone: true,
                    //     //     barierDismisable: false,
                    //     //     message: "Please Reloagin",
                    //     //     onOke: () {
                    //     //       Preferences.clearChace();
                    //     //       Config.loginWith = LoginWith.nonLogin;
                    //     //       Navigator.pop(context);
                    //     //       // SellonRouter.makeFirst(context, HomeScreen());
                    //     //       Navigator.of(context).pushReplacement(
                    //     //         new MaterialPageRoute(
                    //     //             builder: (context) =>
                    //     //                 SplashSellonScreen()),
                    //     //       );
                    //     //     });
                    //   }
                    // });
                  } else {
                    if (isShowMessage == null) {
                      _handleResponseError(
                          '${item['status']}',
                          item['message'],
                          _method,
                          _parameter,
                          _onSuccessListener);
                    }
                    this._onErrorListener!(new Error(
                        this,
                        item['status'] is String
                            ? int.parse(item['status'])
                            : item['status'],
                        "${item['message']}"));
                  }
                }



                if (this._onCompleteListener != null) {
                  this._onCompleteListener!();
                }
              }
            }
          }
          // )
          //     .
          // timeout(timeoutDuration!, onTimeout: () {
          // this._onErrorListener!(new Error(this, 199, 'Time Out'));
          // _handleResponseError(
          //     null, null, _method, _parameter, _onSuccessListener);
        });
        }
        // else {
        //   _errCode++;
        //   _errMessage = 'No Akses';
        // }
      // })
      //     .onError((error, stackTrace) {
      //       // print("object${error.toString()}");
      //     // Future.delayed(Duration(seconds: 1)).then((value) {
      //   if(Config.openMaintence != null && Config.openMaintence == false){
      //     if(context != null){
      //       SellonRouter.makeFirst(context, MaintanceScreen(isErrorApi: true,domainbefore: Config.domainMain == "sellon.net" ? "sellon.store" : "sellon.net" ,key: UniqueKey(),));
      //     }
      //   }else{
      //
      //     if(context != null){
      //       Config.openMaintence = true;
      //       SellonRouter.makeFirst(context, MaintanceScreen(isErrorApi: true,domainbefore: Config.domainMain == "sellon.net" ? "sellon.store" : "sellon.net" ,key: UniqueKey(),));
      //     }
      //   }
          // });
      // });


      // print("result host=> ${result[0].host} adress ==> ${result[0].address} raw ==>  ${result[0].rawAddress}");


    }
  } on SocketException catch (a) {
    print("a ${a.message}");
    // Future.delayed(Duration(seconds: 1)).then((value) {
    //   SellonRouter.makeFirst(context, MaintanceScreen(isErrorApi: true,domainbefore: Config.domainMain == "sellon.net" ? "sellon.store" : "sellon.net" ,));
    // });

    _errCode++;
    _errMessage = 'No Internet';
  } catch (e) {
    // print("object ${e.toString()}");
    _errCode++;
    _errMessage = 'No Internet';
    // Future.delayed(Duration(seconds: 1)).then((value) {
    //   SellonRouter.makeFirst(context, MaintanceScreen(isErrorApi: true,domainbefore: Config.domainMain == "sellon.net" ? "sellon.store" : "sellon.net" ,));
    // });
    // print("heree ");
  }

  if (_errCode > 0) {
    try {
      throw new Exception(_errMessage);
    } catch (ex) {
      this._onExceptionListener!(ex);
    }
  }
}