//
//  CBLVersion.m
//  CouchbaseLite
//
//  Copyright (c) 2018 Couchbase, Inc All rights reserved.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//

#import "CBLVersion.h"

#if TARGET_OS_IPHONE
#import <UIKit/UIKit.h>
#endif

#import "repo_version.h"    // Generated by get_repo_version.sh at build time

@implementation CBLVersion

+ (NSString*) userAgent {
    static NSString* sUserAgent;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
#if TARGET_OS_IPHONE
        UIDevice* device = [UIDevice currentDevice];
        NSString* system = [NSString stringWithFormat: @"%@ %@; %@",
                            device.systemName, device.systemVersion, device.model];
#else
        NSOperatingSystemVersion v = [[NSProcessInfo processInfo] operatingSystemVersion];
        NSString* version = [NSString stringWithFormat:@"%ld.%ld.%ld",
                             v.majorVersion, v.minorVersion, v.patchVersion];
        NSString* system = [NSString stringWithFormat: @"macOS %@", version];
#endif
        NSString* platform = strcmp(CBL_PRODUCT_NAME, "CouchbaseLiteSwift") == (0) ?
        @"Swift" : @"ObjC";
        
        NSString* commit = strlen(GitCommit) > (0) ?
        [NSString stringWithFormat: @"Commit/%.8s%s", GitCommit, GitDirty] : @"NA";
        
        C4StringResult liteCoreVers = c4_getVersion();
        
        sUserAgent = [NSString stringWithFormat: @"CouchbaseLite/%s (%@; %@) Build/%d %@ LiteCore/%.*s",
                      CBL_VERSION_STRING, platform, system, CBL_BUILD_NUMBER, commit,
                      (int)liteCoreVers.size, (char*)liteCoreVers.buf];
        c4slice_free(liteCoreVers);
    });
    return sUserAgent;
}

@end
