import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:mwf_app/service/assets.dart';
import 'package:mwf_app/service/color.dart';
import 'package:mwf_app/service/header.dart';
import 'package:mwf_app/service/screen.dart';
import 'package:mwf_app/service/shadow.dart';
import 'package:mwf_app/model/map_location.dart';

class MapNavigation extends StatefulWidget {
  @override
  _MapNavigationState createState() => _MapNavigationState();
}

class _MapNavigationState extends State<MapNavigation> {
  static LatLng _initialPosition;
  final Set<Marker> _markers = {};
  static LatLng _lastMapPosition = _initialPosition;

  var myLatitude;
  var myLongitude;

  @override
  void initState() {
    super.initState();

//    getLocation();
    loadData(); // ดึงข้อมูล
  }

//  getLocation()async {
//    var geolocator = Geolocator();
//    var locationOptions =
//        LocationOptions(accuracy: LocationAccuracy.high, distanceFilter: 10);
//
//    StreamSubscription<Position> positionStream = geolocator
//        .getPositionStream(locationOptions)
//        .listen((Position position) {
//          print(position);
////      print(position == null
////          ? 'Unknown'
////          : position.latitude.toString() +
////              ', ' +
////              position.longitude.toString());
//    });
//  }

  loadData() async {
    final list = await MapLocation.getData(); // ไปเรียกฟังชั่นดึงข้อมูลจาก api
    setState(() {
      list.forEach((v) {
        final mapsList = MapLocation.fromJson(v);

//        MapLocation.data.add(mapsList); // loop เก็บข้อมูล
      });
    });
  }

  @override
  Completer<GoogleMapController> _controller = Completer();
  static final CameraPosition _kGooglePlex = CameraPosition(
    target: LatLng(37.42796133580664, -122.085749655962),
    zoom: 14.4746,
  );

  static final CameraPosition _kLake = CameraPosition(
      bearing: 192.8334901395799,
      target: LatLng(37.43296265331129, -122.08832357078792),
      tilt: 59.440717697143555,
      zoom: 19.151926040649414);
  Widget build(BuildContext context) {
    double _width = MediaQuery.of(context).size.width;
    double _height = MediaQuery.of(context).size.height;

    return Material(
      color: AppColors.bgColor,
      child: Stack(
        children: <Widget>[
          Header.header1(context),
          Header.mainMenu(context),
          Container(
//            color: Colors.black,
            width: _width,
            height: mediaQuery(context, 'h', 1800),
            margin: EdgeInsets.only(
              top: mediaQuery(context, 'h', 1000),
//              left: mediaQuery(context, 'w', 60),
//              right: mediaQuery(context, 'w', 60),
            ),
            child: SingleChildScrollView(
              child: Column(
                children: <Widget>[
                  Container(
                    height: mediaQuery(context, "h", 665),
                    child: GoogleMap(
                      markers: {
                        Marker(
                            markerId: MarkerId("1"),
                            position:
                                LatLng(37.43296265331129, -122.08832357078792),
                            infoWindow:
                                InfoWindow(title: "ชื่อ	", snippet: "")),
                      },
                      mapType: MapType.normal,
                      myLocationEnabled: true,
                      initialCameraPosition: CameraPosition(
                        target: LatLng(37.43296265331129, -122.08832357078792),
                        zoom: 15,
                      ),
                      onMapCreated: (GoogleMapController controller) {
                        _controller.complete(controller);
                      },
                    ),
                  ),
                  _buildSizeBox(context),
                  _buildSizeBox(context),
                  _buildSizeBox(context),
                  _buildSizeBox(context),
                  _buildSizeBox(context),
                  _buildSizeBox(context),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Image.asset(
                        AppAssets.MapPlace,
                        width: mediaQuery(context, "w", 300),
                        height: mediaQuery(context, "h", 300),
//                        fit: BoxFit.cover,
                      ),
                      SizedBox(
                        width: 10,
                      ),
                      GestureDetector(
                        onTap: () {
                          _getUserLocation();
                        },
                        child: Image.asset(
                          AppAssets.MapPoint,
                          width: mediaQuery(context, "w", 300),
                          height: mediaQuery(context, "h", 300),
//                        fit: BoxFit.cover,
                        ),
                      ),
                    ],
                  ),
                  _buildSizeBox(context),
                  _buildSizeBox(context),
                  _buildSizeBox(context),
                  _buildSizeBox(context),
                  GestureDetector(
                    onTap: () {
                      saveMapLocation(context);
                    },
                    child: Container(
                      width: mediaQuery(context, 'w', 1005),
                      height: mediaQuery(context, 'h', 150),
                      decoration: BoxDecoration(
                        borderRadius: new BorderRadius.all(
                          Radius.circular(
                            mediaQuery(context, 'h', 100),
                          ),
                        ),
                        boxShadow: [
                          appShadow(),
                        ],
                        color: AppColors.color,
                      ),
                      child: Center(
                        child: Text(
                          'บันทึก',
                          textAlign: TextAlign.center,
                          style: TextStyle(
                            fontSize: mediaQuery(context, 'h', 50),
                            color: Colors.white,
                          ),
                        ),
                      ),
                    ),
                  ),
                  Container(
                    width: 150,
                    height: 150,
//                    color: Colors.red,
                  )
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  _buildSizeBox(context) {
    return SizedBox(
      height: mediaQuery(context, "h", 15),
    );
  }

  void _getUserLocation() async {
    var position = await Geolocator()
        .getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
    List<Placemark> placeMark = await Geolocator()
        .placemarkFromCoordinates(position.latitude, position.longitude);
    setState(() {
      _initialPosition = LatLng(position.latitude, position.longitude);
//      print('${placeMark[0].position}');
    });
    setState(() {
      myLatitude = position.latitude;
      myLongitude = position.longitude;
    });
  }

  saveMapLocation(context) async {
    _getUserLocation();
    Map<String, dynamic> data = {
      "latitude": myLatitude,
      "longtitude": myLongitude
    };
    MapLocation.saveData(context, data);
  }
} //class
