/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * Generated with the TypeScript template
 * https://github.com/react-native-community/react-native-template-typescript
 *
 * @format
 */

import React, {useEffect} from 'react';
import {
  SafeAreaView,
  StatusBar,
  StyleSheet,
  Text,
  View,
  Switch,
  Button,
  PermissionsAndroid,
  // ToastAndroid,
  // NativeModules,
} from 'react-native';

import Geolocation, {
  GeolocationError,
  // GeolocationResponse,
} from '@react-native-community/geolocation';

import NativeTaskRunner from './specs/NativeTaskRunner';

// const {ForegroundHeadlessModule} = NativeModules;

const Colors = {
  gold: '#fedd1e',
  black: '#000',
  white: '#fff',
  lightGrey: '#ccc',
  blue: '#337AB7',
  brick: '#973920',
};

/// Util class for handling fetch-event peristence in AsyncStorage.
// import Event from './src/Event';
import AsyncStorage from '@react-native-async-storage/async-storage';
import * as Location from 'expo-location';

Geolocation.setRNConfiguration({
  skipPermissionRequests: true,
  locationProvider: 'auto',
});

/* 
function geoLocationPromise(): Promise<GeolocationResponse | GeolocationError> {
  return new Promise((resolve, reject) => {
    Geolocation.getCurrentPosition(
      info => {
        console.log(info);
        resolve(info);
      },
      error => {
        console.log(error);
        reject(error);
      },
      {
        timeout: 20000,
        maximumAge: 0,
        // enableHighAccuracy: true,
      },
    );
  });
}

*/
const requestPermissions = async () => {
  try {
    const granted = await PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
      {
        title: 'Need permission to access location',
        message:
          'Location access is needed ' + 'so we can track your location!',
        buttonNegative: 'Cancel',
        buttonPositive: 'OK',
      },
    );
    const granted2 = await PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.ACCESS_BACKGROUND_LOCATION,
      {
        title: 'Need permission to access location',
        message:
          'Location access is needed ' + 'so we can track your location!',
        buttonNegative: 'Cancel',
        buttonPositive: 'OK',
      },
    );
    if (
      granted === PermissionsAndroid.RESULTS.GRANTED &&
      granted2 === PermissionsAndroid.RESULTS.GRANTED
    ) {
      console.log('You can use the location');
    } else {
      console.log('Location permission denied');
    }
  } catch (err) {
    console.warn(err);
  }
};

const App = () => {
  const [enabled, setEnabled] = React.useState(false);

  useEffect(() => {
    async function getCurrentLocation() {
      let location = await Location.getLastKnownPositionAsync({});
      console.log(location);
    }
    async function xy() {
      try {
        await requestPermissions();
        const x = await AsyncStorage.getItem('locationtask');
        if (x === '1') {
          setEnabled(true);
        } else {
          setEnabled(false);
        }

        getCurrentLocation();
      } catch (error) {
        console.log('Something went wrong', error);
      }
    }

    xy();
  }, []);

  async function onLocPress(): Promise<void> {
    try {
      // const locInfo = (await geoLocationPromise()) as GeolocationResponse;
      // ToastAndroid.show(
      //   `lat-${locInfo.coords.latitude};long-${locInfo.coords.longitude}`,
      //   5000,
      // );
      if (enabled) {
        return;
      }

      try {
        // ForegroundHeadlessModule.startService();
        NativeTaskRunner.startService();
        setEnabled(true);
        AsyncStorage.setItem('locationtask', '1');
      } catch (error) {
        console.log(error);
      }
      console.log('Did it run?');
    } catch (error) {
      const g = error as GeolocationError;
      if (g.message) {
        console.log(g.message);
      } else {
        console.log(error);
      }
    }
  }

  function onLocStop() {
    try {
      // ForegroundHeadlessModule.stopService();
      NativeTaskRunner.stopService();
      setEnabled(false);
      AsyncStorage.setItem('locationtask', '0');
    } catch (error) {
      console.log(error);
    }
  }

  return (
    <SafeAreaView style={{flex: 1, backgroundColor: Colors.gold}}>
      <StatusBar barStyle={'light-content'}></StatusBar>
      <View style={styles.container}>
        <View style={styles.toolbar}>
          <Text style={styles.title}>BGFetch Demo</Text>
          <Button title="Loc" onPress={onLocPress} />
          <Button title="Stop" onPress={onLocStop} />
        </View>
        <View style={styles.toolbar}>
          <Switch value={enabled} />
        </View>
      </View>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flexDirection: 'column',
    flex: 1,
  },
  title: {
    fontSize: 24,
    flex: 1,
    fontWeight: 'bold',
    color: Colors.black,
  },
  eventList: {
    flex: 1,
    backgroundColor: Colors.white,
  },
  event: {
    padding: 10,
    borderBottomWidth: 1,
    borderColor: Colors.lightGrey,
  },
  taskId: {
    color: Colors.blue,
    fontSize: 16,
    fontWeight: 'bold',
  },
  headless: {
    fontWeight: 'bold',
  },
  remark: {
    color: Colors.brick,
  },
  timestamp: {
    color: Colors.black,
  },
  toolbar: {
    height: 57,
    flexDirection: 'row',
    paddingLeft: 10,
    paddingRight: 10,
    alignItems: 'center',
    backgroundColor: Colors.gold,
  },
});

export default App;
