//
//  SearchMedicalCentreViewController.m
//  MedicalHelp
//
//  Created by Tops on 7/10/14.
//  Copyright (c) 2014 mac. All rights reserved.
//
//  dentist,doctor,gym,hair_care,hospital,pharmacy,physiotherapist,veterinary_care
//
//  2014-07-11 13:49:56.460 MedicalHelp[1509:13d03] latitude =  23.5879607
//  2014-07-11 13:49:56.460 MedicalHelp[1509:13d03] longitude = 72.36932519999999

#import "SearchMedicalCentreViewController.h"

#define kGOOGLE_API_KEY @"AIzaSyDetv1PG-XxPIkB3h-pyHcbmRTDHh_GrN0"

@implementation SearchMedicalCentreViewController

@synthesize searchMapBar,mapView,placeType,SegMapType,arrayPlaces;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    arrayPlaces=[[NSMutableArray alloc]init];
    //set map type
    self.mapView.mapType = MKMapTypeStandard;
    
    //Make this controller the delegate for the map view.
    self.mapView.delegate = self;
    
    // Ensure that you can view your own location in the map view.
    [self.mapView setShowsUserLocation:YES];
    
    //Instantiate a location object.
    locationManager = [[CLLocationManager alloc] init];
    
    //Make this controller the delegate for the location manager.
    [locationManager setDelegate:self];
    
    //Set some parameters for the location object.
    [locationManager setDistanceFilter:kCLDistanceFilterNone];
    [locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    
    firstLaunch=YES;
    
    //To hide keyboard
    UITapGestureRecognizer *g = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hideKeyboard)];
    
    [self.mapView addGestureRecognizer:g];

    //Create Searchbar On Navigation Bar
    searchMapBar = [[UISearchBar alloc] initWithFrame:CGRectMake(-5.0, 0.0, 320.0, 44.0)];
    searchMapBar.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    UIView *searchBarView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 310.0, 44.0)];
    searchBarView.autoresizingMask = 0;
    searchMapBar.delegate = self;
    [searchBarView addSubview:searchMapBar];
    self.navigationItem.titleView = searchBarView;
    
    //By Default No Segment Selected
    [SegMapType setSelectedSegmentIndex:UISegmentedControlNoSegment];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)mapView:(MKMapView *)mv didAddAnnotationViews:(NSArray *)views {
    
    //Zoom back to the user location after adding a new set of annotations.
    //Get the center point of the visible map.
    CLLocationCoordinate2D centre = [mv centerCoordinate];
    
    MKCoordinateRegion region;
    
    //If this is the first launch of the app, then set the center point of the map to the user's location.
    if (firstLaunch) {
        region = MKCoordinateRegionMakeWithDistance(locationManager.location.coordinate,1000,1000);
        firstLaunch=NO;
    }else {
        //Set the center point to the visible region of the map and change the radius to match the search radius passed to the Google query string.
        region = MKCoordinateRegionMakeWithDistance(centre,currenDist,currenDist);
    }
    //Set the visible region of the map.
    [mv setRegion:region animated:YES];
}

-(void) queryGooglePlaces: (NSString *) googleType {
    
    // Build the url string to send to Google. NOTE: The kGOOGLE_API_KEY is a constant that should contain your own API key that you obtain from Google. See this link for more info:
    // https://developers.google.com/maps/documentation/places/#Authentication
    
    NSString *url = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/search/json?location=%f,%f&radius=%@&types=%@&sensor=true&key=%@", currentCentre.latitude, currentCentre.longitude, [NSString stringWithFormat:@"%i", currenDist], googleType, kGOOGLE_API_KEY];
    
    //NSLog(@"URL IS %@",url);
    
    //Formulate the string as a URL object.
    NSURL *googleRequestURL=[NSURL URLWithString:url];
    
    // Retrieve the results of the URL.
    dispatch_async(kBgQueue, ^{
        NSData* data = [NSData dataWithContentsOfURL: googleRequestURL];
        [self performSelectorOnMainThread:@selector(fetchedData:) withObject:data waitUntilDone:YES];
    });
}

-(void)fetchedData:(NSData *)responseData {
    
    //parse out the json data
    NSError* error;
    NSDictionary* json = [NSJSONSerialization
                          JSONObjectWithData:responseData
                          
                          options:kNilOptions
                          error:&error];
    
    //The results from Google will be an array obtained from the NSDictionary object with the key "results".
    NSArray* places = [json objectForKey:@"results"];
    
    //Write out the data to the console.
//    NSLog(@"Google Data: %@", places);
    
    [self plotPositions:places];
}

-(void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated {
    
    //Get the east and west points on the map so you can calculate the distance (zoom level) of the current map view.
    MKMapRect mRect = self.mapView.visibleMapRect;
    MKMapPoint eastMapPoint = MKMapPointMake(MKMapRectGetMinX(mRect), MKMapRectGetMidY(mRect));
    MKMapPoint westMapPoint = MKMapPointMake(MKMapRectGetMaxX(mRect), MKMapRectGetMidY(mRect));
    
    //Set your current distance instance variable.
    currenDist = MKMetersBetweenMapPoints(eastMapPoint, westMapPoint);
    
    //Set your current center point on the map instance variable.
    currentCentre = self.mapView.centerCoordinate;
}

-(void)plotPositions:(NSArray *)data {
    
    // 1 - Remove any existing custom annotations but not the user location blue dot.
    for (id<MKAnnotation> annotation in mapView.annotations) {
        if ([annotation isKindOfClass:[MapPoint class]]) {
            [mapView removeAnnotation:annotation];
        }
    }
    
    [arrayPlaces removeAllObjects];
    // 2 - Loop through the array of places returned from the Google API.
    for (int i=0; i<[data count]; i++) {
        
        //Retrieve the NSDictionary object in each index of the array.
        NSDictionary* place = [data objectAtIndex:i];
        
        // 3 - There is a specific NSDictionary object that gives us the location info.
        NSDictionary *geo = [place objectForKey:@"geometry"];
        
        // Get the lat and long for the location.
        NSDictionary *loc = [geo objectForKey:@"location"];
        
        // 4 - Get your name and address info for adding to a pin.
        NSString *name=[place objectForKey:@"name"];
        NSString *vicinity=[place objectForKey:@"vicinity"];
        
        // Create a special variable to hold this coordinate info.
        CLLocationCoordinate2D placeCoord;
        
        // Set the lat and long.
        float lat=[[loc objectForKey:@"lat"] floatValue];
        placeCoord.latitude=lat;
        float longi=[[loc objectForKey:@"lng"] floatValue];
        placeCoord.longitude=longi;
        
        //Save into array
        NSArray *arr=[[NSArray alloc]initWithObjects:name,vicinity,[NSNumber numberWithFloat:lat ],[NSNumber numberWithFloat:longi], nil];
       
        [arrayPlaces addObject:arr];
        
        // 5 - Create a new annotation.
        MapPoint *placeObject = [[MapPoint alloc] initWithName:name address:vicinity coordinate:placeCoord];
        [mapView addAnnotation:placeObject];
    }
}

-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {
    // Define your reuse identifier.
    static NSString *identifier = @"MapPoint";
    
    if ([annotation isKindOfClass:[MapPoint class]]) {
        MKPinAnnotationView *annotationView = (MKPinAnnotationView *) [self.mapView dequeueReusableAnnotationViewWithIdentifier:identifier];
        if (annotationView == nil) {
            annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:identifier];
        } else {
            annotationView.annotation = annotation;
        }
        annotationView.enabled = YES;
        annotationView.canShowCallout = YES;
        annotationView.animatesDrop = YES;
        return annotationView;
    }
    return nil;
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    //hide KeyBoard
    [self hideKeyboard];
    
    NSString *fUrl = [JFUrlUtil encodeUrl:[NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/geocode/json?address=%@&sensor=true",searchBar.text]];
    
    NSURL *url = [[NSURL alloc]initWithString:fUrl];
    
    NSString *jsonString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
    
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:nil];
    
    NSString *status=[dict objectForKey:@"status"];
    
    if([status isEqualToString:@"OK"])
    {
        NSArray *arrResult=[dict objectForKey:@"results"];
        
        NSDictionary *ResultData=[arrResult objectAtIndex:0];
        
        NSDictionary *Gementry=[ResultData objectForKey:@"geometry"];
        
        NSDictionary *location=[Gementry objectForKey:@"location"];
        
        NSString *lat=[location objectForKey:@"lat"];
        
        NSString *lng=[location objectForKey:@"lng"];
        
        NSString *faddress=[ResultData objectForKey:@"formatted_address"];
        
        //Create Region and Set on map
        MKCoordinateRegion region = {{0.0, 0.0},{0.0,0.0}};
        
        region.center.latitude = [lat floatValue];
        region.center.longitude = [lng floatValue];
        
        region.span.latitudeDelta = 0.02f;
        region.span.longitudeDelta = 0.02f;
        
        [mapView setRegion:region];
        
        //now create annotation
        MapPoint *annotation = [[MapPoint alloc]initWithName:@"This Location" address:faddress coordinate:region.center];
        
        [mapView addAnnotation:annotation];
    }
    else
    {
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Error" message:@"Location Not Found" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
        [alert show];
    }
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return true;
}

-(void)hideKeyboard
{
    //Hide keyboard on single tap on mapView
    [self.searchMapBar resignFirstResponder];
}

- (IBAction)segChangeMapType:(UISegmentedControl *)sender {
    
    switch (sender.selectedSegmentIndex) {
        case 0:
            self.mapView.mapType = MKMapTypeStandard;
            break;
            
        case 1:
            self.mapView.mapType = MKMapTypeSatellite;
            break;
            
        case 2:
            self.mapView.mapType = MKMapTypeHybrid;
            break;
            
        default:
            break;
    }
}

- (IBAction)segChangePlaceType:(UISegmentedControl *)sender {

    switch (sender.selectedSegmentIndex) {
            
        case 0:
           placeType = @"hospital";
            break;
            
        case 1:
            placeType = @"pharmacy";
            break;
            
        case 2:
            placeType = @"gym";
            break;
            
        default:
            break;
    }
    
    [self queryGooglePlaces:placeType];
}

- (IBAction)btnListAllPlace:(id)sender {
    
    MedicalInfoTableViewController *v1 = [[MedicalInfoTableViewController alloc]init];
    
    v1.arrayPlaces = self.arrayPlaces;
    
    v1.placeType = self.placeType;
    
    [self.navigationController pushViewController:v1 animated:YES];
    
}
@end
