//
//  ZYJQNNetworkInfo.m
//  ZYJHappyDNS
//
//  Created by bailong on 15/6/25.
//  Copyright (c) 2015年 Qiniu Cloud Storage. All rights reserved.
//

#import <arpa/inet.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>

#import "ZYJQNIP.h"
#import "ZYJQNNetworkInfo.h"

const int kZYJQNNO_NETWORK = -1;
const int kZYJQNWIFI = 1;
const int kZYJQNMOBILE = 2;

const int kZYJQNISP_GENERAL = 0;
const int kZYJQNISP_CTC = 1;
const int kZYJQNISP_DIANXIN = kZYJQNISP_CTC;
const int kZYJQNISP_CNC = 2;
const int kZYJQNISP_LIANTONG = kZYJQNISP_CNC;
const int kZYJQNISP_CMCC = 3;
const int kZYJQNISP_YIDONG = kZYJQNISP_CMCC;
const int kZYJQNISP_OTHER = 999;

#define IPLength 64

static char previousIp[IPLength] = {0};
static NSString *lock = @"";

@implementation ZYJQNNetworkInfo

- (instancetype)init:(int)connecton provider:(int)provider {
    if (self = [super init]) {
        _networkConnection = connecton;
        _provider = provider;
    }
    return self;
}

+ (instancetype)noNet {
    return [[ZYJQNNetworkInfo alloc] init:kZYJQNNO_NETWORK provider:kZYJQNISP_GENERAL];
}

+ (instancetype)normal {
    return [[ZYJQNNetworkInfo alloc] init:kZYJQNISP_GENERAL provider:kZYJQNISP_GENERAL];
}

- (BOOL)isEqualToInfo:(ZYJQNNetworkInfo *)info {
    if (self == info)
        return YES;
    return self.provider == info.provider && self.networkConnection == info.networkConnection;
}

- (BOOL)isEqual:(id)other {
    if (other == self)
        return YES;
    if (!other || ![other isKindOfClass:[self class]])
        return NO;
    return [self isEqualToInfo:other];
}

+ (BOOL)isNetworkChanged {
    @synchronized(lock) {
        char local[IPLength] = {0};
        int err = ZYJQN_localIp(local, sizeof(local));
        if (err != 0) {
            return YES;
        }
        if (memcmp(previousIp, local, sizeof(local)) != 0) {
            memcpy(previousIp, local, sizeof(local));
            return YES;
        }
        return NO;
    }
}

+ (NSString *)getIp {
    return [ZYJQNIP local];
}
@end
