mobileApplicationsKonectarApp/lib/main.dart

291 lines
10 KiB
Dart

import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:path_provider/path_provider.dart';
import 'package:provider/provider.dart';
import 'package:pwa_ios/model/interaction_config_data.dart';
import 'package:pwa_ios/model/interaction_data.dart';
import 'package:pwa_ios/model/json_form_data.dart';
import 'package:pwa_ios/model/save_interaction.dart';
import 'package:pwa_ios/model/userdata_model.dart';
import 'package:pwa_ios/repository/hive_repository.dart';
import 'package:pwa_ios/utils/mockapi.dart';
import 'package:pwa_ios/utils/sessionmanager.dart';
import 'package:pwa_ios/utils/util.dart';
import 'package:pwa_ios/viewmodel/configprovider.dart';
import 'package:pwa_ios/viewmodel/interactionprovider.dart';
import 'package:pwa_ios/viewmodel/loginprovider.dart';
import 'package:pwa_ios/viewmodel/viewinteractionprovider.dart';
import 'package:pwa_ios/views/home_screen.dart';
import 'package:pwa_ios/views/konectarpage.dart';
import 'package:pwa_ios/views/login.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:openid_client/openid_client.dart';
import 'package:flutter_web_plugins/url_strategy.dart';
import 'package:internet_connection_checker/internet_connection_checker.dart';
//import 'openid/openid_io.dart' if (dart.library.html) 'openid_browser.dart';
const keycloakUri = 'https://sso.konectar.io/auth/realms/konectar';
const scopes = ['profile'];
Credential? credential;
late final Client client;
UserInfo? userInfo;
Timer? mytimer;
// Future<Client> getClient() async {
// var uri = Uri.parse(keycloakUri);
// if (!kIsWeb && Platform.isAndroid)
// var clientId = 'appwildcard';
// var issuer = await Issuer.discover(uri);
// return Client(issuer, clientId);
// }
// _asyncMethod() async {
// //client = await getClient();
// var credential = await authenticate(client, scopes: scopes);
// userInfo = await credential.getUserInfo();
// // setState(() {
// // });
// }
Future main() async {
WidgetsFlutterBinding.ensureInitialized();
//await execute(InternetConnectionChecker());
// Create customized instance which can be registered via dependency injection
// final InternetConnectionChecker customInstance =
// InternetConnectionChecker.createInstance(
// checkTimeout: const Duration(milliseconds: 1),
// checkInterval: const Duration(milliseconds: 1),
// );
// // Check internet connection with created instance
// await execute(customInstance);
await Hive.initFlutter();
Hive.registerAdapter(SaveInteractionAdapter());
Hive.registerAdapter(InteractionConfigDataAdapter());
Hive.registerAdapter(InteractionResultDataAdapter());
Hive.registerAdapter(FormFieldDataAdapter());
Hive.registerAdapter(ValidationAdapter());
Hive.registerAdapter(SectionListAdapter());
Hive.registerAdapter(InputClassAdapter());
Hive.registerAdapter(InteractionWidgetAdapter());
Hive.registerAdapter(UserDataAdapter());
Hive.registerAdapter(SendSaveJsonAdapter());
Hive.registerAdapter(MultipleSectionListAdapter());
Hive.registerAdapter(SaveAdapter());
Hive.registerAdapter(SaveInteractionFormJsonAdapter());
// await Hive.openBox('InteractionDataBox');
// await Hive.openBox<UserData>("UserDataBox");
//await Hive.openBox('InteractionConfigDataBox');
await Hive.openBox<InteractionConfigData>('InteractionConfigDataBox');
// final ConfigDataProvider configDataProvider = ConfigDataProvider();
final ConfigDataProvider configDataProvider = ConfigDataProvider();
//configDataProvider = fetchInteactionConfigData();
// final ViewInteractionProvider viewInteractionProvider =
// ViewInteractionProvider();
// List<SaveInteraction> savedList =
// await viewInteractionProvider.getAllRecords();
// SendSavedDataJson json = SendSavedDataJson(data: savedList);
// print(json.toString());
// await MockApiCall().postFormData(json).then((value) async {
// await configDataProvider.initConfigUIData().then((value) {
// // activateTimer();
// });
// });
await configDataProvider.initConfigUIData();
// activateTimer();
// await provider.initConfigUIData();
if (!kIsWeb &&
kDebugMode &&
defaultTargetPlatform == TargetPlatform.android) {
await InAppWebViewController.setWebContentsDebuggingEnabled(kDebugMode);
}
// await initDirectory();
// await PushNotificationService().setupInteractedMessage();
// RemoteMessage? initialMessage =
// await FirebaseMessaging.instance.getInitialMessage();
// if (initialMessage != null) {
// // App received a notification when it was killed
// }
WidgetsFlutterBinding.ensureInitialized();
// FirebaseMessaging.instance.getToken().then((value) {
// String? token = value;
// print("token: $token");
// });
usePathUrlStrategy();
// client = await getClient();
// //credential = await getRedirectResult(client, scopes: scopes);
// credential = await authenticate(client, scopes: scopes);
// userInfo = await credential!.getUserInfo();
//runApp(const MyApp());
SharedPreferences.getInstance().then((instance) {
//StorageService().sharedPreferencesInstance = instance;
bool isloggedIn = instance.getBool('isloggedin') ?? false;
runApp(
MultiProvider(
providers: [
ChangeNotifierProvider(create: (_) => InteractionProvider()),
ChangeNotifierProvider(create: (_) => LoginProvider()),
ChangeNotifierProvider(create: (_) => ViewInteractionProvider()),
ChangeNotifierProvider(create: (_) => ConfigDataProvider()),
ChangeNotifierProvider<HiveDataRepository>(
create: (_) => HiveDataRepository(
Hive.box<InteractionConfigData>('InteractionConfigDataBox'))),
],
child: MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Dynamic Links Example',
initialRoute: '/',
routes: <String, WidgetBuilder>{
'/': (BuildContext context) => FutureBuilder<bool>(
future: SessionManager().isLoggedIn(),
builder: (context, snapshot) {
print("Data_is : $snapshot");
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator();
} else if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
final isLoggedIn = snapshot.data ?? false;
print("isLoggedIn_is : $isLoggedIn");
return isLoggedIn ? HomeScreen() : LoginScreen();
}
},
), //userInfo != null ? const Home() : OpenidScreen(credential: credential,),
// '/details': (BuildContext context) => const HomeScreen(),
},
),
),
);
});
}
cancelTimer() {
mytimer?.cancel();
}
activateTimer() {
mytimer = Timer.periodic(const Duration(minutes: 5), (timer) async {
//code to run on every 2 minutes 5 seconds
final ConfigDataProvider configDataProvider = ConfigDataProvider();
final ViewInteractionProvider viewInteractionProvider =
ViewInteractionProvider();
List<SaveInteraction> savedList =
await viewInteractionProvider.getAllRecords();
SendSavedDataJson json = SendSavedDataJson(data: savedList);
print(json.toString());
await MockApiCall().postFormData(json).then((value) async {
await configDataProvider.initConfigUIData().then((value) {
// activateTimer();
});
});
print("Interval called 2 mins");
});
print("timer");
print(mytimer?.isActive);
}
Future<void> execute(
InternetConnectionChecker internetConnectionChecker,
) async {
// Simple check to see if we have Internet
// ignore: avoid_print
print('''The statement 'this machine is connected to the Internet' is: ''');
final bool isConnected = await InternetConnectionChecker().hasConnection;
// ignore: avoid_print
print(
isConnected.toString(),
);
// returns a bool
// We can also get an enum instead of a bool
// ignore: avoid_print
print(
'Current status: ${await InternetConnectionChecker().connectionStatus}',
);
// Prints either InternetConnectionStatus.connected
// or InternetConnectionStatus.disconnected
// actively listen for status updates
final StreamSubscription<InternetConnectionStatus> listener =
InternetConnectionChecker().onStatusChange.listen(
(InternetConnectionStatus status) {
switch (status) {
case InternetConnectionStatus.connected:
// ignore: avoid_print
print('Data connection is available.');
break;
case InternetConnectionStatus.disconnected:
// ignore: avoid_print
print('You are disconnected from the internet.');
break;
}
},
);
// close listener after 30 seconds, so the program doesn't run forever
await Future<void>.delayed(const Duration(seconds: 30));
await listener.cancel();
}
class Home extends StatefulWidget {
const Home({Key? key}) : super(key: key);
@override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> with WidgetsBindingObserver {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: Center(
child: TextButton(
onPressed: () {
// Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (context) => MyApp()));
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const MyApp()),
);
},
child: Text('click'),
),
),
),
);
}
@override
void dispose() {
Hive.close();
super.dispose();
}
}