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
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
// lib.rs
//
// Copyright © 2018
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.

extern crate curl;
extern crate regex;
extern crate serde_json;

pub mod from_json;
pub mod query;
pub mod requests;
pub mod validate;

use query::{EntityQuery, SearchQuery};
use std::{error::Error, fmt};

const USER_AGENT_BASE: &'static str = "Wikibase-RS/0.3.0";

#[derive(Debug)]
pub enum WikibaseError {
    Configuration(String),
    Request(String),
    Serialization(String),
    Validation(String),
}

impl Error for WikibaseError {}

impl fmt::Display for WikibaseError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:?}", self)
    }
}

/// Configurations for Wikibase RS
///
/// The Configuration struct holds all the parameters that can can be
/// customized. The api_url is the api endpoint or a particular Wikibase
/// instance. It defaults to Wikidata.
#[derive(Debug)]
pub struct Configuration {
    api_url: String,
    user_agent_prefix: String,
}

impl Configuration {
    pub fn new(user_agent_prefix: &str) -> Result<Configuration, WikibaseError> {
        let valid_user_agent_prefix = validate::validate_user_agent(&user_agent_prefix)?;

        Ok(Self {
            api_url: "https://www.wikidata.org/w/api.php".to_string(),
            user_agent_prefix: valid_user_agent_prefix.to_string(),
        })
    }

    pub fn api_url(&self) -> &str {
        &self.api_url
    }

    pub fn set_api_url<S: Into<String>>(&mut self, api_url: S) {
        self.api_url = api_url.into();
    }

    /// Returns the complete user agent that is used for requests
    ///
    /// The full user agent is a combination of the user agent prefix,
    /// that is set by a library and the Wikibase RS user agent.
    /// For example: `my_bot/0.2 Wikibase-RS/1.0.2`.
    pub fn user_agent(&self) -> String {
        format!("{} {}", &self.user_agent_prefix, USER_AGENT_BASE)
    }

    pub fn user_agent_prefix(&self) -> &str {
        &self.user_agent_prefix
    }
}

#[derive(Debug)]
pub enum Value {
    Coordinate(Coordinate),
    MonoLingual(MonoLingualText),
    Entity(EntityValue),
    Quantity(QuantityValue),
    StringValue(String),
    Time(TimeValue),
}

/// DataValueType
///
/// Is the type that is stored together with a value in the DataValue.
///
/// # JSON Mapping
///
/// EntityId = "wikibase-entityid"
/// GlobeCoordinate = "globecoordinate"
/// MonoLingualText = "monolingualtext"
/// Quantity = "quantity"
/// StringType = "string"
/// Time = "time"
///
/// # Example
///
/// ```
/// let data_value_type = wikibase::DataValueType::new_from_str("quantity");
/// ```
#[derive(Debug)]
pub enum DataValueType {
    EntityId,
    GlobeCoordinate,
    MonoLingualText,
    Quantity,
    StringType,
    Time,
}

impl DataValueType {
    pub fn new_from_str(string_value: &str) -> Result<DataValueType, WikibaseError> {
        match string_value {
            "globecoordinate" => Ok(DataValueType::GlobeCoordinate),
            "monolingualtext" => Ok(DataValueType::MonoLingualText),
            "quantity" => Ok(DataValueType::Quantity),
            "string" => Ok(DataValueType::StringType),
            "wikibase-entityid" => Ok(DataValueType::EntityId),
            "time" => Ok(DataValueType::Time),
            _ => Err(WikibaseError::Serialization(
                "Data value type could not be matched".to_string(),
            )),
        }
    }

    pub fn string_value(&self) -> String {
        match *self {
            DataValueType::EntityId => "wikibase-entityid".to_string(),
            DataValueType::GlobeCoordinate => "globecoordinate".to_string(),
            DataValueType::MonoLingualText => "monolingualtext".to_string(),
            DataValueType::Quantity => "quantity".to_string(),
            DataValueType::StringType => "string".to_string(),
            DataValueType::Time => "time".to_string(),
        }
    }
}

/// Coordinate
///
/// Used in Wikibase to store point coordinates on a globe. Consists of
/// latitude, longitude and a globe. Precision and altitude are optional.
///
/// The globe is given as a link to an entity
/// (e.g. http://www.wikidata.org/entity/Q2).
///
/// # Documentation
///
/// * https://www.wikidata.org/wiki/Help:Data_type#Globe_coordinate
/// * https://www.mediawiki.org/wiki/Wikibase/DataModel#Geographic_locations
///
/// # Example
///
/// ```
/// let mut coordinate = wikibase::Coordinate::new(Some(100f64), "http://www.wikidata.org/entity/Q2".to_string(), 12f64, 6f64, Some(0f64));
/// ```
#[derive(Debug)]
pub struct Coordinate {
    altitude: Option<f64>,
    globe: String,
    latitude: f64,
    longitude: f64,
    precision: Option<f64>,
}

impl Coordinate {
    fn new_from_json(
        object: &serde_json::Map<std::string::String, serde_json::Value>,
    ) -> Result<Coordinate, WikibaseError> {
        let mut altitude = None;
        let mut precision = None;

        if object["altitude"].is_null() == false {
            let altitude_string = match object["altitude"].as_str() {
                Some(value) => value,
                None => return Err(WikibaseError::Serialization("Altitude".to_string())),
            };

            let altitude_number: f64 = match altitude_string.parse() {
                Ok(value) => value,
                Err(error) => {
                    return Err(WikibaseError::Serialization(
                        error.description().to_string(),
                    ));
                }
            };

            altitude = Some(altitude_number);
        }

        let latitude = match object["latitude"].as_f64() {
            Some(value) => value,
            None => return Err(WikibaseError::Serialization("Latitude".to_string())),
        };

        let longitude = match object["longitude"].as_f64() {
            Some(value) => value,
            None => return Err(WikibaseError::Serialization("Longitude".to_string())),
        };

        if object["precision"].is_null() == false {
            precision = match object["precision"].as_f64() {
                Some(value) => Some(value),
                None => return Err(WikibaseError::Serialization("Precision".to_string())),
            };
        }

        let globe = match object["globe"].as_str() {
            Some(value) => value,
            None => return Err(WikibaseError::Serialization("Globe".to_string())),
        };

        Ok(Self {
            altitude,
            globe: globe.to_string(),
            latitude,
            longitude,
            precision,
        })
    }

    pub fn new(
        altitude: Option<f64>,
        globe: String,
        latitude: f64,
        longitude: f64,
        precision: Option<f64>,
    ) -> Coordinate {
        Self {
            altitude,
            globe,
            latitude,
            longitude,
            precision,
        }
    }

    pub fn altitude(&self) -> &Option<f64> {
        &self.altitude
    }

    pub fn globe(&self) -> &str {
        &self.globe
    }

    pub fn latitude(&self) -> &f64 {
        &self.latitude
    }

    pub fn longitude(&self) -> &f64 {
        &self.longitude
    }

    pub fn precision(&self) -> &Option<f64> {
        &self.precision
    }

    pub fn set_altitude(&mut self, altitude: Option<f64>) {
        self.altitude = altitude;
    }

    pub fn set_globe<S: Into<String>>(&mut self, globe: S) {
        self.globe = globe.into();
    }

    pub fn set_latitude(&mut self, latitude: f64) {
        self.latitude = latitude;
    }

    pub fn set_longitude(&mut self, longitude: f64) {
        self.longitude = longitude;
    }

    pub fn set_precision(&mut self, precision: Option<f64>) {
        self.precision = precision;
    }
}

/// Monolingual Text
///
/// Monolingual text is similar to the LocaleString used for
/// labels and descriptions. It holds a language key and a text.
///
/// # Documentation
///
/// https://www.wikidata.org/wiki/Help:Data_type#Monolingual_text
///
/// # Example
///
/// ```
/// let text = wikibase::MonoLingualText::new("Bécs", "hu");
/// ```
#[derive(Debug)]
pub struct MonoLingualText {
    language: String,
    text: String,
}

impl MonoLingualText {
    fn new_from_json(
        object: &serde_json::Map<std::string::String, serde_json::Value>,
    ) -> Result<MonoLingualText, WikibaseError> {
        let language = match object["language"].as_str() {
            Some(value) => value,
            None => return Err(WikibaseError::Serialization("Language".to_string())),
        };

        let text = match object["text"].as_str() {
            Some(value) => value,
            None => return Err(WikibaseError::Serialization("Text".to_string())),
        };

        Ok(Self {
            language: language.to_string(),
            text: text.to_string(),
        })
    }

    pub fn new<S: Into<String>>(text: S, language: S) -> MonoLingualText {
        Self {
            text: text.into(),
            language: language.into(),
        }
    }

    pub fn language(&self) -> &str {
        &self.language
    }

    pub fn set_language<S: Into<String>>(&mut self, language: S) {
        self.language = language.into();
    }

    pub fn set_text<S: Into<String>>(&mut self, text: S) {
        self.text = text.into();
    }

    pub fn text(&self) -> &str {
        &self.text
    }
}

/// EntityType
///
/// Type of the a Wikidata entity. Is either Item or Property.
///
/// # JSON Mapping
///
/// Item = `item`
/// Property = `property`
///
/// # Example
///
/// ```
/// let entity_type = wikibase::EntityType::Item;
/// let item = wikibase::EntityType::new_from_str("Q256");
/// let property = wikibase::EntityType::new_from_str("P18");
/// ```
#[derive(Debug)]
pub enum EntityType {
    Item,
    Property,
}

impl EntityType {
    pub fn new_from_str(type_string: &str) -> Option<EntityType> {
        match type_string {
            "item" => Some(EntityType::Item),
            "property" => Some(EntityType::Property),
            _ => None,
        }
    }

    pub fn new_from_id(id_string: &str) -> Result<EntityType, WikibaseError> {
        let first_char = match id_string.chars().nth(0) {
            Some(value) => value,
            None => {
                return Err(WikibaseError::Validation(
                    "Error getting first character of string".to_string(),
                ));
            }
        };

        match first_char {
            'P' => Ok(EntityType::Property),
            'Q' => Ok(EntityType::Item),
            _ => Err(WikibaseError::Serialization(
                "Error matching entity type".to_string(),
            )),
        }
    }

    pub fn string_value(&self) -> String {
        match *self {
            EntityType::Item => "item".to_string(),
            EntityType::Property => "property".to_string(),
        }
    }
}

/// Statement Rank
///
/// The rank each statement has on Wikidata. Default is Normal.
/// https://www.wikidata.org/wiki/Help:Ranking
#[derive(Debug)]
pub enum StatementRank {
    Deprecated,
    Normal,
    Preferred,
}

/// Statement
///
/// A Wikidata statement has a main statement (the `main_snak`),
/// and qualifiers and references. In Wikidata terminology
/// only a claim with references is a statement.
#[derive(Debug)]
pub struct Statement {
    claim_type: String,
    rank: StatementRank,
    main_snak: Snak,
    qualifiers: Vec<Snak>,
    references: Vec<Reference>,
}

/// DataValue
///
/// The DataValue holds a value_type (wikibase-item, ...) and the
/// actual value. It is stored within a Snak struct.
///
/// # Json mapping
///
/// "value" - value
/// "type" - value_type
#[derive(Debug)]
pub struct DataValue {
    value: Value,
    value_type: DataValueType,
}

/// LocaleString
///
/// Structure holding a language key and a value string. Used for
/// labels and descriptions of Wikidata items.
#[derive(Debug)]
pub struct LocaleString {
    language: String,
    value: String,
}

/// Wikibase entity (item or property)
///
/// Items and properties are very similar in Wikibase. They have a prefix
/// followed by an ID, labels, descriptions, aliases. Both items and properties
/// have statements that may have qualifiers. Statements can also contain
/// references, in which case they are called statements, but are handled
/// the same way in the API.
///
/// Items can also have sitelinks to various projects. On Wikidata for example
/// an item can link to Wikpedia, Wikisource, Wiktionary in various languages.
/// The actual wiki-pages attached to an item or property can't be accessed
/// at the moment. This includes the edit-history, the talk page and the
/// pages various settings (protection, locked, ...).
///
/// Entities can be created manually or from a JSON that needs to have the
/// same structure as the Wikibase API.
///
/// # Example
///
/// ```
/// let item = wikibase::Entity::new("Q2807".to_string(), vec![], vec![], vec![], vec![], None, false);
/// ```
#[derive(Debug)]
pub struct Entity {
    id: String,
    labels: Vec<LocaleString>,
    descriptions: Vec<LocaleString>,
    aliases: Vec<LocaleString>,
    claims: Vec<Statement>,
    sitelinks: Option<Vec<SiteLink>>,
    missing: bool,
}

/// Sitelink
///
/// A sitelink contains the id of the connected site, which is usually a
/// combination of language code (skwiki, skwikiquote) and the project id or
/// for monolingual projects just the project-id (commonswiki, wikidatawiki).
///
/// The title of the page is stored as a string. A sitelink can also have
/// a list of badges that the page has. Badges are item-ids and for example
/// given to featured pages (Given as an ID e.g. "Q17437798").
///
/// For an overview of all allowed sites see:
/// https://www.wikidata.org/w/api.php?action=paraminfo&modules=wbsetlabel
///
/// # Example
///
/// ```
/// let sitelink = wikibase::SiteLink::new("dewiki", "Österreich", vec!["Q17437798".to_string()]);
/// ```
#[derive(Debug)]
pub struct SiteLink {
    badges: Vec<String>,
    site: String,
    title: String,
}

impl SiteLink {
    pub fn new<S: Into<String>>(site: S, title: S, badges: Vec<String>) -> SiteLink {
        Self {
            badges,
            site: site.into(),
            title: title.into(),
        }
    }
}

/// QuantityValue
///
/// Holds the quantity value of a claim.
///
/// # Json mapping
///
/// unit = `http://www.wikidata.org/entity/Q11574`
#[derive(Debug)]
pub struct QuantityValue {
    amount: f64,
    lower_bound: Option<f64>,
    unit: String,
    upper_bound: Option<f64>,
}

/// Reference
///
/// A Reference holds a vector of Snaks.
#[derive(Debug)]
pub struct Reference {
    snaks: Vec<Snak>,
}

/// SnakType
///
/// The SnakType is set whether a claim has an actual value (H has one proton),
/// or the value is unknown (Cleopatra's shoe size) or non-existant (Earth's
/// eye color).
///
/// # Json mapping
///
/// UnknownValue = "somevalue"
/// NoValue = "novalue"
/// Value = "value"
#[derive(Debug)]
pub enum SnakType {
    NoValue,
    UnknownValue,
    Value,
}

impl SnakType {
    pub fn string_mapping(&self) -> &str {
        match self {
            &SnakType::Value => &"Value",
            &SnakType::NoValue => &"No Value",
            &SnakType::UnknownValue => &"Some Value",
        }
    }
}

/// Search-result entity
///
/// Struct that holds all the data about a search result. The difference
/// to a normal entity is that no claims and sitelinks are returned. The
/// label, description and aliases are only returned for one language.
#[derive(Debug)]
pub struct SearchResultEntity {
    id: String,
    entity_type: EntityType,
    label: LocaleString,
    description: Option<LocaleString>,
    aliases: Vec<LocaleString>,
}

impl SearchResultEntity {
    pub fn new<S: Into<String>>(
        id: S,
        entity_type: EntityType,
        label: LocaleString,
        description: Option<LocaleString>,
        aliases: Vec<LocaleString>,
    ) -> SearchResultEntity {
        Self {
            id: id.into(),
            entity_type,
            label,
            description,
            aliases,
        }
    }

    pub fn aliases(&self) -> &Vec<LocaleString> {
        &self.aliases
    }

    pub fn description(&self) -> &Option<LocaleString> {
        &self.description
    }

    pub fn id(&self) -> &str {
        &self.id
    }

    pub fn label(&self) -> &LocaleString {
        &self.label
    }

    pub fn set_aliases(&mut self, aliases: Vec<LocaleString>) {
        self.aliases = aliases;
    }

    pub fn set_descriptions(&mut self, description: Option<LocaleString>) {
        self.description = description;
    }

    pub fn set_labels(&mut self, label: LocaleString) {
        self.label = label;
    }
}

/// Search results
///
/// A struct holding a vector of search result entities.
#[derive(Debug)]
pub struct SearchResults {
    results: Vec<SearchResultEntity>,
}

impl SearchResults {
    pub fn new(results: Vec<SearchResultEntity>) -> SearchResults {
        Self { results }
    }

    /// Takes a wikibase entity query and returns a result of an error.
    pub fn new_from_query(
        query: &SearchQuery,
        configuration: &Configuration,
    ) -> Result<SearchResults, WikibaseError> {
        let request_result = requests::wikibase_request(&query.url(&configuration), &configuration);

        let json_response = match request_result {
            Ok(value) => value,
            Err(error) => return Err(error),
        };

        from_json::search_result_entities_from_json(&json_response, &query)
    }

    pub fn results(&self) -> &Vec<SearchResultEntity> {
        &self.results
    }
}

/// Snak
///
/// Each Snak has a property and a value (`data_value`). Each claim has
/// one main snak and an arbitrary amount of snaks for qualifiers and
/// references.
///
/// # Data type
///
/// - commonsMedia
/// - wikibase-item
#[derive(Debug)]
pub struct Snak {
    datatype: String,
    property: String,
    snak_type: SnakType,
    data_value: Option<DataValue>,
}

/// EntityValue
///
/// Target of claim that can either be an item or a property entity.
///
/// # Example
///
/// ```
/// let item = wikibase::EntityValue::new(wikibase::EntityType::Item, "Q212730");
/// let property = wikibase::EntityValue::new(wikibase::EntityType::Property, "P4539");
/// ```
#[derive(Debug)]
pub struct EntityValue {
    entity_type: EntityType,
    id: String,
}

/// Time value
///
/// Struct holding time information. The time is given as a string in the
/// format "+1864-12-24T00:00:00Z". The calendar model is given as a link
/// to an entity http://www.wikidata.org/entity/Q1985727.
///
/// # Wikibase documentation
///
/// https://www.mediawiki.org/wiki/Wikibase/DataModel#Dates_and_times
#[derive(Debug)]
pub struct TimeValue {
    after: u64,
    before: u64,
    calendarmodel: String,
    precision: u64,
    time: String,
    timezone: u64,
}

impl LocaleString {
    fn new<S: Into<String>>(language: S, value: S) -> LocaleString {
        Self {
            language: language.into(),
            value: value.into(),
        }
    }

    pub fn language(&self) -> &str {
        &self.language
    }

    pub fn value(&self) -> &str {
        &self.value
    }
}

impl QuantityValue {
    fn new_from_object(
        value: &serde_json::Map<std::string::String, serde_json::Value>,
    ) -> Result<QuantityValue, WikibaseError> {
        let amount = match from_json::float_from_json(&value, "amount") {
            Some(value) => value,
            None => return Err(WikibaseError::Serialization("Amount".to_string())),
        };

        let lower_bound = from_json::float_from_json(&value, "lowerBound");
        let upper_bound = from_json::float_from_json(&value, "upperBound");

        Ok(Self {
            amount,
            lower_bound,
            unit: value["unit"].as_str().unwrap_or_else(|| "").to_string(),
            upper_bound,
        })
    }

    pub fn new<S: Into<String>>(
        amount: f64,
        lower_bound: Option<f64>,
        unit: S,
        upper_bound: Option<f64>,
    ) -> QuantityValue {
        Self {
            amount,
            lower_bound,
            unit: unit.into(),
            upper_bound,
        }
    }

    pub fn amount(&self) -> &f64 {
        &self.amount
    }

    pub fn lower_bound(&self) -> &Option<f64> {
        &self.lower_bound
    }

    pub fn set_amount(&mut self, amount: f64) {
        self.amount = amount;
    }

    pub fn set_lower_bound(&mut self, lower_bound: Option<f64>) {
        self.lower_bound = lower_bound;
    }

    pub fn set_unit<S: Into<String>>(&mut self, unit: S) {
        self.unit = unit.into();
    }

    pub fn set_upper_bound(&mut self, upper_bound: Option<f64>) {
        self.upper_bound = upper_bound;
    }

    pub fn unit(&self) -> &str {
        &self.unit
    }

    pub fn upper_bound(&self) -> &Option<f64> {
        &self.upper_bound
    }
}

fn entity_from_query(
    query: &EntityQuery,
    configuration: &Configuration,
) -> Result<Entity, WikibaseError> {
    let json_response = requests::wikibase_request(&query.url(&configuration), &configuration)?;
    let id = &query.ids()[0];
    let json_entity = &json_response["entities"][id];

    from_json::entity_from_json(json_entity)
}

impl Entity {
    pub fn new(
        id: String,
        labels: Vec<LocaleString>,
        descriptions: Vec<LocaleString>,
        aliases: Vec<LocaleString>,
        claims: Vec<Statement>,
        sitelinks: Option<Vec<SiteLink>>,
        missing: bool,
    ) -> Entity {
        Self {
            id,
            labels,
            descriptions,
            aliases,
            claims,
            sitelinks,
            missing,
        }
    }

    fn new_empty() -> Entity {
        Self {
            id: "".to_string(),
            labels: vec![],
            descriptions: vec![],
            aliases: vec![],
            claims: vec![],
            sitelinks: None,
            missing: false,
        }
    }

    /// Takes a single Q-Id or P-Id and returns an item result.
    ///
    /// # Example
    ///
    /// ```
    /// let configuration = wikibase::Configuration::new("Automatic-Testing/1.0").unwrap();
    /// let item = wikibase::Entity::new_from_id("Q47532594", &configuration);
    /// ```
    pub fn new_from_id<S: Into<String>>(
        id: S,
        configuration: &Configuration,
    ) -> Result<Entity, WikibaseError> {
        let ids = vec![id.into()];
        let query = EntityQuery::new(ids, "en");

        entity_from_query(&query, &configuration)
    }

    /// Takes a vector of Q-Ids or P-Ids and returns an item result.
    pub fn new_from_ids(
        ids: Vec<String>,
        configuration: &Configuration,
    ) -> Result<Entity, WikibaseError> {
        let query = EntityQuery::new(ids, "en");

        entity_from_query(&query, &configuration)
    }

    /// Takes a entity query and returns an item.
    pub fn new_from_query(
        query: &EntityQuery,
        configuration: &Configuration,
    ) -> Result<Entity, WikibaseError> {
        entity_from_query(&query, &configuration)
    }

    pub fn aliases(&self) -> &Vec<LocaleString> {
        &self.aliases
    }

    pub fn label_in_locale(&self, locale: &str) -> Option<&str> {
        for label in &self.labels {
            if label.language() == locale {
                return Some(label.value());
            }
        }

        None
    }

    pub fn description_in_locale(&self, locale: &str) -> Option<&str> {
        for description in &self.descriptions {
            if description.language() == locale {
                return Some(description.value());
            }
        }

        None
    }

    fn set_aliases(&mut self, aliases: Vec<LocaleString>) {
        self.aliases = aliases;
    }

    fn set_claims(&mut self, claims: Vec<Statement>) {
        self.claims = claims;
    }

    fn set_descriptions(&mut self, descriptions: Vec<LocaleString>) {
        self.descriptions = descriptions;
    }

    fn set_id(&mut self, id: String) {
        self.id = id;
    }

    fn set_labels(&mut self, labels: Vec<LocaleString>) {
        self.labels = labels;
    }

    fn set_missing(&mut self, missing: bool) {
        self.missing = missing;
    }

    pub fn set_sitelinks(&mut self, sitelinks: Option<Vec<SiteLink>>) {
        self.sitelinks = sitelinks;
    }

    pub fn sitelinks(&self) -> &Option<Vec<SiteLink>> {
        &self.sitelinks
    }

    pub fn claims(&self) -> &Vec<Statement> {
        &self.claims
    }

    pub fn id(&self) -> &str {
        &self.id
    }

    pub fn missing(&self) -> &bool {
        &self.missing
    }
}

impl TimeValue {
    fn new_from_object(
        value: &serde_json::Map<std::string::String, serde_json::Value>,
    ) -> TimeValue {
        Self {
            after: value["after"].as_u64().unwrap_or_else(|| 0),
            before: value["before"].as_u64().unwrap_or_else(|| 0),
            calendarmodel: value["calendarmodel"]
                .as_str()
                .unwrap_or_else(|| "")
                .to_string(),
            precision: value["precision"].as_u64().unwrap_or_else(|| 0),
            time: value["time"].as_str().unwrap_or_else(|| "").to_string(),
            timezone: value["timezone"].as_u64().unwrap_or_else(|| 0),
        }
    }

    pub fn new<S: Into<String>>(
        after: u64,
        before: u64,
        calendarmodel: S,
        precision: u64,
        time: S,
        timezone: u64,
    ) -> TimeValue {
        Self {
            after,
            before,
            calendarmodel: calendarmodel.into(),
            precision,
            time: time.into(),
            timezone,
        }
    }

    pub fn after(&self) -> &u64 {
        &self.after
    }

    pub fn before(&self) -> &u64 {
        &self.before
    }

    pub fn calendarmodel(&self) -> &str {
        &self.calendarmodel
    }

    pub fn precision(&self) -> &u64 {
        &self.precision
    }

    pub fn set_after(&mut self, after: u64) {
        self.after = after;
    }

    pub fn set_before(&mut self, before: u64) {
        self.before = before;
    }

    pub fn set_calendarmodel<S: Into<String>>(&mut self, calendarmodel: S) {
        self.calendarmodel = calendarmodel.into();
    }

    pub fn set_precision(&mut self, precision: u64) {
        self.precision = precision;
    }

    pub fn set_time<S: Into<String>>(&mut self, time: S) {
        self.time = time.into();
    }

    pub fn set_timezone(&mut self, timezone: u64) {
        self.timezone = timezone;
    }

    pub fn time(&self) -> &str {
        &self.time
    }

    pub fn timezone(&self) -> &u64 {
        &self.timezone
    }
}

impl EntityValue {
    pub fn new<S: Into<String>>(entity_type: EntityType, id: S) -> EntityValue {
        Self {
            entity_type,
            id: id.into(),
        }
    }

    pub fn new_from_object(
        value: &serde_json::Map<std::string::String, serde_json::Value>,
    ) -> Result<EntityValue, WikibaseError> {
        let entity_type_string = match value["entity-type"].as_str() {
            Some(value) => value,
            None => {
                return Err(WikibaseError::Serialization(
                    "Entity type is not a string".to_string(),
                ));
            }
        };

        let entity_type = match EntityType::new_from_str(entity_type_string) {
            Some(value) => value,
            None => {
                return Err(WikibaseError::Serialization(
                    "Entity type did not match".to_string(),
                ));
            }
        };

        let id = match value["id"].as_str() {
            Some(value) => value,
            None => {
                return Err(WikibaseError::Serialization(
                    "Id is not a string".to_string(),
                ));
            }
        };

        Ok(Self {
            entity_type,
            id: id.to_string(),
        })
    }

    pub fn entity_type(&self) -> &EntityType {
        &self.entity_type
    }

    pub fn id(&self) -> &str {
        &self.id
    }

    pub fn set_entity_type(&mut self, entity_type: EntityType) {
        self.entity_type = entity_type;
    }

    pub fn set_id<S: Into<String>>(&mut self, id: S) {
        self.id = id.into();
    }
}

impl Reference {
    pub fn new(snaks: Vec<Snak>) -> Reference {
        Self { snaks }
    }

    pub fn set_snaks(&mut self, snaks: Vec<Snak>) {
        self.snaks = snaks;
    }
}

impl DataValue {
    pub fn new(value_type: DataValueType, value: Value) -> DataValue {
        Self { value_type, value }
    }

    pub fn set_value(&mut self, value: Value) {
        self.value = value;
    }

    pub fn set_value_type(&mut self, value_type: DataValueType) {
        self.value_type = value_type;
    }

    pub fn value(&self) -> &Value {
        &self.value
    }

    pub fn value_type(&self) -> &DataValueType {
        &self.value_type
    }
}

/// Main snak data structure
///
/// The main snak is an object that contains the main statement
/// information: the property, datatype and the value. The
/// statement, qualifiers and references are the 3 snaks of a
/// statement object.
impl Snak {
    pub fn new<S: Into<String>>(
        datatype: S,
        property: S,
        snak_type: SnakType,
        data_value: Option<DataValue>,
    ) -> Snak {
        Self {
            datatype: datatype.into(),
            property: property.into(),
            snak_type,
            data_value,
        }
    }

    pub fn datatype(&self) -> &str {
        &self.datatype
    }

    pub fn data_value(&self) -> &Option<DataValue> {
        &self.data_value
    }

    pub fn property(&self) -> &str {
        &self.property
    }

    pub fn set_datatype(&mut self, datatype: &str) {
        self.datatype = datatype.to_string();
    }

    pub fn set_data_value(&mut self, data_value: Option<DataValue>) {
        self.data_value = data_value;
    }

    pub fn set_property(&mut self, property: &str) {
        self.property = property.to_string();
    }

    pub fn set_snak_type(&mut self, snak_type: SnakType) {
        self.snak_type = snak_type;
    }

    pub fn snak_type(&self) -> &SnakType {
        &self.snak_type
    }
}

impl Statement {
    pub fn new<S: Into<String>>(
        claim_type: S,
        rank: StatementRank,
        main_snak: Snak,
        qualifiers: Vec<Snak>,
        references: Vec<Reference>,
    ) -> Statement {
        Self {
            claim_type: claim_type.into(),
            rank,
            main_snak,
            qualifiers,
            references,
        }
    }

    pub fn set_claim_type(&mut self, claim_type: &str) {
        self.claim_type = claim_type.to_string();
    }

    pub fn set_rank(&mut self, rank: StatementRank) {
        self.rank = rank;
    }

    pub fn set_datatype(&mut self, datatype: &str) {
        self.main_snak.datatype = datatype.to_string();
    }

    pub fn property(&self) -> &str {
        &self.main_snak.property
    }

    pub fn set_property(&mut self, property: &str) {
        self.main_snak.property = property.to_string();
    }

    pub fn set_main_snak(&mut self, snak: Snak) {
        self.main_snak = snak;
    }

    pub fn add_qualifier_snak(&mut self, snak: Snak) {
        self.qualifiers.push(snak);
    }

    pub fn set_qualifier_snaks(&mut self, snaks: Vec<Snak>) {
        self.qualifiers = snaks;
    }

    pub fn set_references(&mut self, references: Vec<Reference>) {
        self.references = references;
    }

    pub fn references(&self) -> &Vec<Reference> {
        &self.references
    }

    pub fn qualifiers(&self) -> &Vec<Snak> {
        &self.qualifiers
    }

    pub fn main_snak(&self) -> &Snak {
        &self.main_snak
    }
}