forked from zhiphe/Potatso-iOS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ConfigurationGroup.swift
105 lines (85 loc) · 2.96 KB
/
ConfigurationGroup.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
//
// ConfigurationGroup.swift
// Potatso
//
// Created by LEI on 4/6/16.
// Copyright © 2016 TouchingApp. All rights reserved.
//
import RealmSwift
public enum ConfigurationGroupError: ErrorType {
case InvalidConfigurationGroup
case EmptyName
case NameAlreadyExists
}
extension ConfigurationGroupError: CustomStringConvertible {
public var description: String {
switch self {
case .InvalidConfigurationGroup:
return "Invalid config group"
case .EmptyName:
return "Empty name"
case .NameAlreadyExists:
return "Name already exists"
}
}
}
public class ConfigurationGroup: BaseModel {
public dynamic var editable = true
public dynamic var name = ""
public dynamic var defaultToProxy = true
public dynamic var dns = ""
public let proxies = List<Proxy>()
public let ruleSets = List<RuleSet>()
public override static func indexedProperties() -> [String] {
return ["name"]
}
public func validate(inRealm realm: Realm) throws {
guard name.characters.count > 0 else {
throw ConfigurationGroupError.EmptyName
}
guard realm.objects(ConfigurationGroup).filter("name = '\(name)'").first == nil else {
throw ConfigurationGroupError.NameAlreadyExists
}
}
}
extension ConfigurationGroup: CustomStringConvertible {
public override var description: String {
return name
}
}
extension ConfigurationGroup {
public convenience init(dictionary: [String: AnyObject], inRealm realm: Realm) throws {
self.init()
guard let name = dictionary["name"] as? String else {
throw ConfigurationGroupError.InvalidConfigurationGroup
}
self.name = name
if realm.objects(RuleSet).filter("name = '\(name)'").first != nil {
self.name = ConfigurationGroup.dateFormatter.stringFromDate(NSDate())
}
if let proxyName = dictionary["proxy"] as? String, proxy = realm.objects(Proxy).filter("name = '\(proxyName)'").first {
self.proxies.removeAll()
self.proxies.append(proxy)
}
if let ruleSetsName = dictionary["ruleSets"] as? [String] {
for ruleSetName in ruleSetsName {
if let ruleSet = realm.objects(RuleSet).filter("name = '\(ruleSetName)'").first {
self.ruleSets.append(ruleSet)
}
}
}
if let defaultToProxy = dictionary["defaultToProxy"] as? NSString {
self.defaultToProxy = defaultToProxy.boolValue
}
if let dns = dictionary["dns"] as? String {
self.dns = dns
}
if let dns = dictionary["dns"] as? [String] {
self.dns = dns.joinWithSeparator(",")
}
}
}
extension ConfigurationGroup: Equatable {}
public func ==(lhs: ConfigurationGroup, rhs: ConfigurationGroup) -> Bool {
return lhs.uuid == rhs.uuid
}