execute method

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

Implementation

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

  // if (_onSuccessListener != null) {
    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 (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 == null || _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.post, _parameter);
    }
  }

  var requestParams = "";
  var index = 0;

  // _parameter.data.forEach((key, val) {
  //   index++;
  //   requestParams += "$key=$val${index == _parameter.data.length ? '' : '&'}";
  // });
  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(_method == "pelanggan/check_version_mobile_app/"){
        //   _parameter.set('nation_code', "65");
        // }

        if (Config.apiKey != null) {
          _parameter.set('apikey', Config.apiKey!);
        }
        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);
        }
        Preferences.getApiKey().then((apikey) {
          if(apikey == null || apikey == "null"){
          }else{
            _parameter.set('apikey', apikey);
          }
          Preferences.getApises().then((apises) {
            if(apises == null || apises == "null"){
            }else{
              _parameter.set('apisess', apises);
            }
            executeFuture(
                _method, _parameter, _onSuccessListener)
                .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}");
                  }
                  Map item = jsonDecode(body);
                  int code = 200;
                  if (item['errorCode'] is String) {
                    code = int.parse(item['errorCode']);
                  } else if (item['errorCode'] is int) {
                    code = item['errorCode'];
                  }
                  if (code == 200) {
                    if (_method == "pelanggan/login/") {
                      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 Api.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 Api(context2: _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 Api.createDefaultParams(
                                      (parameter) async {
                                    // top
                                    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");
                                    // }
                                    Preferences.getApises().then((apisess2) async {
                                      if (apisess2 == "null" || apisess2 == null){

                                      }else{
                                        _parameter.set('apisess', apisess2);
                                      }
                                      ApiGameSellon api2 = ApiGameSellon(_context!);
                                      api2.setErrorListener((error) {
                                        this._onErrorListener!(new Error(this,
                                            error.errCode, error.errMessage));
                                      });
                                      await api2.execute(
                                          _method, _parameter,
                                              (response) {
                                            int status = response.data()["status"];
                                            if (status == 200) {
                                              Success success = response;
                                              this._onSuccessListener(success);
                                            }
                                          },
                                          isShowMessage: _method.contains(
                                              "pelanggan/login_sosmedv2")
                                              ? false
                                              : true);
                                    });
                                    // _parameter.set("timezone", Helper().dateNowChange());


                                  });
                            });
                      });
                    }
                    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') {
                      //     if (_context != null) {
                      //       Helper().modalSellOn(_context,
                      //           alone: true,
                      //           barierDismisable: false,
                      //           message: Languanges.of(_context).pleaseRelogin,
                      //           onOke: () {
                      //             Preferences.clearChace();
                      //             Config.loginWith = LoginWith.nonLogin;
                      //             if(Navigator.canPop(context)){
                      //               SellonRouter.makeFirst(context,SplashSellonScreen());
                      //             }else{
                      //               SellonRouter.makeFirst(context, SplashSellonScreen());
                      //             }
                      //             // 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';
      }
    }
  } on SocketException catch (_) {
    _errCode++;
    _errMessage = 'No Internet';
  } catch (e) {
    _errCode++;
    _errMessage = 'No Internet';
  }

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