//
//  MapViewController.m
//  k-observer-iphone
//
//  Created by vvv ооо on 26.08.12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "MapViewController.h"
#import "AppDelegate.h"

#include "ObserverClientCpp.h"

//extern boost::mutex UpdatingMapMutex;

//extern std::vector<TUserInfo> UserInfoArr;
//extern std::vector<TUserInfo> AlarmUserInfoArr;
/*
void SwitchMapToAlarm();
void SwitchMapToCommon();

bool IsAlarmMap();*/

extern TObserverClient ObserverClientClass;

extern AppDelegate* appDelegate;

@interface MapViewController ()

@end

@implementation MapViewController

@synthesize MapRefreshTimer = _MapRefreshTimer;
@synthesize spinner = _spinner;

- (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.
    
    UISegmentedControl* segmentedControl = (UISegmentedControl*)[self.view viewWithTag:3];
    [segmentedControl addTarget:self action:@selector(onAlarmSelectorChanged) forControlEvents:UIControlEventValueChanged];
    
    UIWebView* webView = (UIWebView*)[self.view viewWithTag:2];
    
    
    NSString* filePath = [[NSBundle mainBundle] pathForResource:@"script" ofType:@"html"];
    
    NSString *htmlString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
    
    NSString* lon_str = [NSString stringWithFormat:@"%f", [appDelegate.observerClient GetBaseLon]];
    NSString* lat_str = [NSString stringWithFormat:@"%f", [appDelegate.observerClient GetBaseLat]];
    NSString* zoom_str = [NSString stringWithFormat:@"%d", [appDelegate.observerClient GetBaseZoom]];
    
    
    htmlString = [htmlString stringByReplacingOccurrencesOfString:@"<<<LON>>>" withString:lon_str];
    htmlString = [htmlString stringByReplacingOccurrencesOfString:@"<<<LAT>>>" withString:lat_str];
    htmlString = [htmlString stringByReplacingOccurrencesOfString:@"<<<ZOOM>>>" withString:zoom_str];
    
    [webView loadHTMLString:htmlString baseURL:nil];
    
    [webView setDelegate:self];
    
    CGPoint p = webView.center;
    
    
    self.spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    
    [self.spinner setCenter:p]; // I do this because I'm in landscape mode
    [webView addSubview:self.spinner]; // spinner is not visible until started
    
    [self.spinner startAnimating];

        
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewDidAppear:(BOOL)animated
{
    [appDelegate.observerClient StartMapHeartbeatTimer];
    
    self.MapRefreshTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(refreshMap) userInfo:nil repeats:YES];
}


- (void)viewDidDisappear:(BOOL)animated
{
    [appDelegate.observerClient StopMapHeartbeatTimer];
    
    self.MapRefreshTimer = nil;

}

-(void)refreshMap
{
    ObserverClientClass.UpdatingMapMutex.lock();
    
    UIWebView* webView = (UIWebView*)[self.view viewWithTag:2];
    
    [webView stringByEvaluatingJavaScriptFromString:@"Clear();"];


    if ([appDelegate.observerClient IsAlarmMap])
    {
    
    for (std::vector<TUserInfo>::iterator i = ObserverClientClass.AlarmUserInfoArr.begin(); i != ObserverClientClass.AlarmUserInfoArr.end(); ++i)
    {
        NSString* posX = [NSString stringWithFormat:@"%f", i->PosX];
        NSString* posY = [NSString stringWithFormat:@"%f", i->PosY];
        NSString* mapState = [NSString stringWithFormat:@"%d", i->MapState];
        
        
        NSString* State;
        
    
        if (i->MapState == 0)
        {
            State = @"Мобильная группа";
        }
        else if (i->MapState == 1)
        {
            State = @"Наблюдатель";
        }
        else if (i->MapState == 2)
        {
            State = @"Тревога";
        }
        else if (i->MapState == 3)
        {
            State = @"Тревога - Удаление с УИК";
        }
        else if (i->MapState == 4)
        {
            State = @"Тревога - Вброс";
        }
        else if (i->MapState == 5)
        {
            State = @"Тревога - Карусель";
        }
        else if (i->MapState == 6)
        {
            State = @"Тревога - Нападение";
        }
        else
        {
            State = @"Тревога";
        }
        
        NSString* text = [NSString stringWithFormat:@"УИК № %d \\n %@ \\n %@ \\n %@ \\n %@ \\n Состояние: %@", 
                i->Uik,
                [NSString stringWithCString:i->LastName.c_str() encoding:NSUTF8StringEncoding],
                [NSString stringWithCString:i->FirstName.c_str() encoding:NSUTF8StringEncoding],
                [NSString stringWithCString:i->MiddleName.c_str() encoding:NSUTF8StringEncoding],
                [NSString stringWithCString:i->PhoneNumber.c_str() encoding:NSUTF8StringEncoding],
                State];
        
        if (i->PosX != 0.f  && i->PosY != 0.f)
        {
            NSString* javaScriptCode = [NSString stringWithFormat:@"AddMarkerWithPopup(%@, %@, %@, \"%@\");", posX, posY, mapState, text];
            
            [webView stringByEvaluatingJavaScriptFromString:javaScriptCode];
        }
    }
        
    }
    else
    {
        for (std::vector<TUserInfo>::iterator i = ObserverClientClass.UserInfoArr.begin(); i != ObserverClientClass.UserInfoArr.end(); ++i)
        {
            NSString* posX = [NSString stringWithFormat:@"%f", i->PosX];
            NSString* posY = [NSString stringWithFormat:@"%f", i->PosY];
            NSString* mapState = [NSString stringWithFormat:@"%d", i->MapState];
            
            if (i->PosX != 0.f  && i->PosY != 0.f)
            {
                NSString* javaScriptCode = [NSString stringWithFormat:@"AddMarker(%@, %@, %@);", posX, posY, mapState];
                
                [webView stringByEvaluatingJavaScriptFromString:javaScriptCode];
            }
        }
    }
    
    
    ObserverClientClass.UpdatingMapMutex.unlock();
}


- (void) onAlarmSelectorChanged
{
    UISegmentedControl* segmentedControl = (UISegmentedControl*)[self.view viewWithTag:3];
  
    UIWebView* webView = (UIWebView*)[self.view viewWithTag:2];

    if (segmentedControl.selectedSegmentIndex == 0)
    {
        [appDelegate.observerClient SwitchMapToCommon];

        [webView stringByEvaluatingJavaScriptFromString:@"DeactivateSelectControl();"];
    }
    else
    {
        [appDelegate.observerClient SwitchMapToAlarm];
        [webView stringByEvaluatingJavaScriptFromString:@"ActivateSelectControl();"];
    }
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [self.spinner stopAnimating];
}

@end
