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

#import "ObserverClient.h"
#import "AppDelegate.h"
#import "MessagesViewController.h"
#import "ConnectViewController.h"
#include "ObserverClientCpp.h"

extern AppDelegate* appDelegate;

TObserverClient ObserverClientClass;


@implementation ObserverClient

-(id)init
{
    self = [super init];
    
    if (self)
    {
        Active = NO;
        CurrentLon = 0.f;
        CurrentLat = 0.f;
    }
    
    return self;
}

-(void)ConnectTo:(NSString*)address onPort:(NSString*)port
{
    if (!Active)
    {
        const char* c_address = [address UTF8String];
        const char* c_port = [port UTF8String];
    
        ObserverClientClass.CreateClientSocket(c_address, c_port);
        
    }
}

-(void)StopTryingConnect
{
    ObserverClientClass.DestroyClientSocket();
    
    [appDelegate.spinner stopAnimating];
    
    UIButton* btn_connect = (UIButton*)[appDelegate.connectViewController.view viewWithTag:3];
    
    UIButton* btn_cancel = (UIButton*)[appDelegate.connectViewController.view viewWithTag:4];
    
    [btn_connect setUserInteractionEnabled:YES];
    
    [btn_cancel setUserInteractionEnabled:NO];
}

-(void)ConnectAutorizationFinished
{
    if (!Active)
    {
        [self StartHeartbeatTimer];
        
        [self PassLonLatToClient];
        
        Active = YES;
    }
}

-(void)Close
{
    if (Active)
    {
        [self StopHeartbeatTimer];
        ObserverClientClass.ClientSocket->BlockForceCloseMessage = true;
        
        ObserverClientClass.DestroyClientSocket();
        Active = NO;
    }
}


-(void)UpdateProfileWithLastName:(NSString*)lastName
                       FirstName:(NSString*)firstName
                      MiddleName:(NSString*)middleName
                     PhoneNumber:(NSString*)phoneNumber
                       UikNumber:(int)uikNumber
                          Status:(int)status
{
    const char* c_lastName = [lastName UTF8String];
    const char* c_firstName = [firstName UTF8String];
    const char* c_middleName = [middleName UTF8String];
    const char* c_phoneNumber = [phoneNumber UTF8String];
    
    ObserverClientClass.UpdateUserInfo(c_lastName, c_firstName, c_middleName, c_phoneNumber, uikNumber, status);
    
}

-(void)SetMapState:(int)mode
{
    ObserverClientClass.ClientSocket->UserInfo.MapState = mode;
}

-(int)GetMapState
{
    return ObserverClientClass.ClientSocket->UserInfo.MapState;
}

-(void)UpdateLon:(float)lon Lat:(float)lat
{
    CurrentLon = lon;
    CurrentLat = lat;
    
    if (Active)
    {
        [self PassLonLatToClient];
    }
}

-(void)PassLonLatToClient
{
    ObserverClientClass.ClientSocket->UserInfo.PosX = CurrentLon;
    ObserverClientClass.ClientSocket->UserInfo.PosY = CurrentLat;
    
}

-(void)StartHeartbeatTimer
{
    ObserverClientClass.RestartHeartbeatTimer();
}

-(void)StopHeartbeatTimer
{
    ObserverClientClass.HeartbeatTimer->cancel();
}

-(void)StartMapHeartbeatTimer
{
    ObserverClientClass.RestartMapHeartbeatTimer();
}

-(void)StopMapHeartbeatTimer
{
    ObserverClientClass.MapHeartbeatTimer->cancel();
}

-(void)SendMessage:(NSString*)msg
{
    const char* c_msg = [msg UTF8String];
    
    ObserverClientClass.SendMessage(c_msg);
}

-(float)GetBaseLon
{
    return ObserverClientClass.ClientSocket->BaseLon;
}

-(float)GetBaseLat
{
    return ObserverClientClass.ClientSocket->BaseLat;
}

-(int)GetBaseZoom
{
    return ObserverClientClass.ClientSocket->BaseZoom;
}

-(void)SwitchMapToAlarm
{
    ObserverClientClass.SwitchMapToAlarm();
}

-(void)SwitchMapToCommon
{
    ObserverClientClass.SwitchMapToCommon();
}

-(bool)IsAlarmMap
{
    return ObserverClientClass.IsAlarmMap();
}


@end


void AppDelegateSendOnConnectionClosed()
{
    [appDelegate.connectViewController OnConnectionClosed];
    
}

void AppDelegateSendOnReceiveQuit()
{
 
    [appDelegate.connectViewController OnReceiveQuit];
}




void AppDelegateAddNewMessage(TUserInfo userInfo, std::string message)
{
    
    @autoreleasepool {
        NSString* str_msg = [NSString stringWithCString:message.c_str() encoding:NSUTF8StringEncoding];
        
        NSString* str_header;
        
        if (userInfo.MapState != 0)
        {
            str_header = [NSString stringWithFormat:@"%d %@", userInfo.Uik, str_msg];
        }
        else
        {
            str_header = [NSString stringWithFormat:@"(МГ) %@", str_msg];
        }
        
        NSString* lastName = [NSString stringWithCString:userInfo.LastName.c_str() encoding:NSUTF8StringEncoding];
        NSString* firstName = [NSString stringWithCString:userInfo.FirstName.c_str() encoding:NSUTF8StringEncoding];
        NSString* middleName = [NSString stringWithCString:userInfo.MiddleName.c_str() encoding:NSUTF8StringEncoding];
        NSString* phoneNumber = [NSString stringWithCString:userInfo.PhoneNumber.c_str() encoding:NSUTF8StringEncoding];
        
        NSString* status;
        
        if (userInfo.MapState == 0)
        {
            status = @"Мобильная группа";
        }
        else
        {
            status = @"Наблюдатель";
        }
        if (userInfo.MapState != 0)
        {
            str_msg = [NSString stringWithFormat:@"УИК %d, %@ %@ %@ %@ %@: %@", userInfo.Uik, lastName, firstName, middleName, phoneNumber, status, str_msg];
        }
        else
        {
            str_msg = [NSString stringWithFormat:@"(МГ), %@ %@ %@ %@ %@: %@", lastName, firstName, middleName, phoneNumber, status, str_msg];
        }
        
        [appDelegate.messagesViewController addMessage:str_msg withHeader:str_header];
        
    }
    
}


void AppDelegateOnAutorizationSend()
{
    [appDelegate gotoMainMenu];
    [appDelegate.observerClient ConnectAutorizationFinished];
}
    