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
// Licensed under the the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>.
// This file may not be copied, modified, or distributed
// except according to those terms.

#![allow(proc_macro_derive_resolution_fallback)]

//! This crate's entire purpose is to seed the
//! [libellis](https://github.com/libellis/libellis-backend) database with fake data (generated by
//! [faker](https://github.com/tikotzky/faker-rs) library).
//!
//! ## Setup
//!
//! You MUST set a `PSQL_URL` environment variable to your libellis postgres database.
//!
//! ### Example
//! ```terminal
//! $ export PSQL_URL=postgres://username:password@localhost/
//! ```
//!
//! Note the ending forward slash which is necessary. You can optionally set this in a `.env` file
//! in the root folder of this project if you are running the project from a local folder.
//!
//! ## Installation
//!
//! You may install this in one of two ways. If you have `cargo` installed then it's very easy. If
//! not, you can install rust and cargo by following this very simple [cargo setup](https://doc.rust-lang.org/cargo/getting-started/installation.html) process.
//! Once you have cargo installed you can install this terminal application by running:
//!
//! ```terminal
//! $ cargo install birdseed
//! ```
//!
//! Optionally you may instead clone this repo and in the root directory build the release version
//! of this crate:
//!
//! ```terminal
//! $ git clone https://github.com/libellis/birdseed.git
//! $ cd birdseed
//! $ cargo build --release
//! ```
//!
//! ## Features
//!
//! ### `setup`
//!
//! You can setup the main libellis and libellis_test databases with this subcommand.  It will
//! attempt to drop both libellis and libellis_test before creating them so be careful! Only use
//! this if you don't need the data in your libellis database and want to start over, or are
//! creating your libellis databases for the first time.
//!
//! ```terminal
//! $ birdseed setup
//! ```
//!
//! ### `rebuild`
//!
//! You can rebuild all tables according to embedded diesel migrations. This drops each table (but
//! does not drop the database itself) and then rebuilds all tables. Note that you must already
//! have `libellis` and `libellis_test` databases for this to work. If you do not have those
//! databases run `birdseed setup` instead.
//!
//! ```terminal
//! $ birdseed rebuild
//! ```
//!
//! `rebuild` by default will rebuild all tables in both your main and test databases. If you would
//! like to specify to only rebuild one database, pass in 'main' or 'test' to the -database
//! argument flag:
//!
//! ### `fences`
//!
//! You can load in fence data from a geojson file with the fences subcommand:
//!
//! ```terminal
//! $ birdseed fences
//! ```
//!
//! By default it looks for a file called `fences.json` in the data folder from the root of this
//! crate. This folder only exists if you cloned the repo.  To specify a filepath yourself pass the
//! -f or -file flag after the fences subcommand:
//!
//! ```terminal
//! $ birdseed fences -f BerkeleyNeighborhoods.json
//! ```
//!
//! Note: This only works if you have a fences table - which would have been setup for you from the
//! most recent migrations when running `birdseed setup` or `birdseed migrate`.
//!
//! ### `feed`
//!
//! You can seed all databases with the `feed` subcommand:
//!
//! ```terminal
//! $ birdseed feed
//! ```
//!
//! We can specify a row count (overriding the default of 1000 rows):
//!
//! ```terminal
//! $ birdseed feed -r 10000
//! ```
//!
//! In this exampe we override the default of 1,000 rows and instead seed 10,000 rows.
//!
//! Note: What the row count really means is that we will seed row count amount of users, surveys
//! and questions, but row count * 4 amount of choices and votes.
//!
//! ```terminal
//! $ birdseed rebuild -database main
//! ```
//!
//! You can also use `-d` for shorthand:
//!
//! ```terminal
//! $ birdseed rebuild -d test
//! ```
//!
//! ### `migrate`
//!
//! To run migrations, use the migrate subcommand (this will update your database schema to the
//! most recent schema).
//!
//! ```terminal
//! $ birdseed migrate
//! ```
//!
//! By default this runs migrations on all databases. To run migrations on only main run:
//!
//! ```terminal
//! $ birdseed migrate -d main
//! ```
//!
//! To run migrations only on the test database run:
//!
//! ```terminal
//! $ birdseed migrate -d test
//! ```
//!
//! ### `clear`
//!
//! You can clear all tables with the `clear` subcommand:
//!
//! ```terminal
//! $ birdseed clear
//! ```
//!
//! ### Icecream
//!
//! For fun and profit you can seed the database with an row count amount of users, a single poll
//! about icecream, and then populate that poll with fake votes from your newly faked user pool,
//! and have all of their votes counted from legitimate randomized locations within the city of San
//! Francisco.
//!
//! ```terminal
//! $ birdseed icecream
//! ```
//!
//! By default the row count is 1000, and can be overriden in the same way as when using the `feed`
//! subcommand:
//!
//! ```terminal
//! $ birdseed icecream -r 10000
//! ```

extern crate structopt;

#[macro_use]
extern crate diesel;
extern crate dotenv;

#[macro_use]
extern crate diesel_migrations;

#[macro_use]
extern crate fake;

extern crate indicatif;
extern crate rand;

use std::fs::File;
use std::io::prelude::*;

use diesel::pg::PgConnection;
use diesel::prelude::*;
use dotenv::dotenv;
use std::env;

use std::process::Command;

use std::error::Error;
use std::io;
use std::io::ErrorKind::InvalidInput;
use structopt::StructOpt;

use geojson::{ GeoJson, Geometry };
use geojson::Value::{ self, Point };

use diesel_geography::types::GeogPoint;

use rand::seq::SliceRandom;
use rand::thread_rng;

use rayon::prelude::*;

use indicatif::{ProgressBar, ProgressStyle};

mod models;
mod pg_pool;
mod schema;

pub use pg_pool::DbConn;
pub use pg_pool::Pool;

embed_migrations!("./migrations");

use self::models::{
    Category, Choice, NewCategory, NewChoice, NewQuestion, NewSurvey, NewUser, NewVote, Question,
    Survey, User, Vote, Fence, NewFence
};

/**
 * DEFINED ERRORS
 */

#[derive(StructOpt, Debug)]
#[structopt(
    name = "birdseed",
    about = "The libellis database seeder",
    long_about = "You can use birdseed to seed a libellis db with junk data!"
)]
/// You can use birdseed to seed a libellis db with junk data!
pub enum Birdseed {
    #[structopt(name = "feed")]
    /// Seeds random data into all tables
    Feed {
        /// How many rows to inject
        #[structopt(short = "r", long = "rows", default_value = "1000")]
        row_count: u32,
    },

    #[structopt(name = "icecream")]
    /// Seeds random icrecream data into all tables
    Icecream {
        /// How many rows to inject
        #[structopt(short = "r", long = "rows", default_value = "1000")]
        row_count: u32,
    },

    #[structopt(name = "fences")]
    /// Loads in fences from a geojson file
    Fences {
        /// The file name to read from - default if not supplied is 
        #[structopt(short = "f", long = "file", default_value = "data/fences.json")]
        filepath: String,
    },

    #[structopt(name = "setup")]
    /// Builds both libellis main and test databases and runs migrations
    Setup,

    #[structopt(name = "migrate")]
    /// Builds both libellis main and test databases and runs migrations
    Migrate {
        /// Which database to run migrations on, main, test, or all
        #[structopt(short = "d", long = "database", default_value = "all")]
        db: String,
    },

    #[structopt(name = "rebuild")]
    /// Rebuilds all tables per most recent schema (embedded in binary)
    Rebuild {
        /// Which database to run rebuild on, main, test, or all
        #[structopt(short = "d", long = "database", default_value = "all")]
        db: String,
    },

    #[structopt(name = "clear")]
    /// Clears all tables in libellis database
    Clear,
}

/// `run` will take in a Birdseed enum config (parsed in `main`) and either clear all tables or
/// populate all tables with number of rows specified in -r (1000 by default)
pub fn run(config: Birdseed) -> Result<(), Box<dyn Error>> {
    match config {
        Birdseed::Feed { row_count } => populate_all(row_count),
        Birdseed::Rebuild { db } => rebuild(&db),
        Birdseed::Setup => setup(),
        Birdseed::Icecream { row_count } => populate_icecream(row_count),
        Birdseed::Fences { filepath } => load_fences(filepath),
        Birdseed::Migrate { db } => migrate(&db),
        Birdseed::Clear => clear_all(),
    }
}

fn setup() -> Result<(), Box<dyn Error>> {
    drop_database("libellis");
    drop_database("libellis_test");
    println!("\r\n                🐦 Creating Main Database 🐦\r\n",);
    setup_database("libellis");
    println!("\r\n                🐦 Creating Test Database 🐦\r\n",);
    setup_database("libellis_test");
    println!("\r\n              🐦 Running Main DB Migrations 🐦\r\n",);
    rebuild("main")?;
    println!("\r\n              🐦 Running Test DB Migrations 🐦\r\n",);
    rebuild("test")?;
    println!("\r\n                        🐦 All Done! 🐦\r\n",);
    Ok(())
}

fn setup_database(database: &str) {
    Command::new("createdb")
        .arg(database)
        .output()
        .expect("failed to create database");
}

fn drop_database(database: &str) {
    Command::new("dropdb")
        .arg(database)
        .output()
        .expect("failed to drop database");
}

fn load_fences(filepath: String) -> Result<(), Box<dyn Error>> {
    use std::io::BufReader;

    dotenv().ok();
    let base_url = env::var("PSQL_URL")?;
    env::set_var("DATABASE_URL", &format!("{}{}", base_url, "libellis"));

    let pool = generate_pool();
    
    // read json file into a string
    let file = File::open(filepath)?;
    let mut buf_reader = BufReader::new(file);
    let mut contents = String::new();
    buf_reader.read_to_string(&mut contents)?;

    // load geo data into fences table
    let conn = pool.get().unwrap();

    load_geo_data(&conn, &contents)?;

    Ok(())
}

fn load_geo_data(conn: &PgConnection, geojson_str: &String) -> Result<(), Box<dyn Error>> {
    use diesel::dsl::sql_query;
    
    match geojson_str.parse::<GeoJson>().unwrap() {
        GeoJson::FeatureCollection(feat_col) => (
            for feature in feat_col.features {
                let property = feature.properties.unwrap();
                let title = property.get("nhood").unwrap().to_string();
                let trimmed_title = title.split('"').collect::<Vec<&str>>()[1];
                let geo_level = 1;
                let geojson = feature.geometry.unwrap();

                let query_str = format!("INSERT INTO fences (title, geo_level, geo) VALUES ('{}', '{}', ST_GeomFromGeoJSON('{}'));", trimmed_title, geo_level, GeoJson::from(geojson).to_string());

                sql_query(query_str).execute(conn)?;
            }
        ),
        _ => (),
    }
    
    Ok(())
}

// Kicks off populating all tables in main database and updating user
// with visual progress bar along the way
fn populate_all(row_count: u32) -> Result<(), Box<dyn Error>> {
    // get the base url and append it with the db name
    dotenv().ok();
    let base_url = env::var("PSQL_URL")?;
    env::set_var("DATABASE_URL", &format!("{}{}", base_url, "libellis"));

    let pool = generate_pool();
    println!("\r\n                  🐦 Seeding All Tables 🐦\r\n",);

    let bar = ProgressBar::new((row_count * 11) as u64);
    bar.set_style(
        ProgressStyle::default_bar()
            .template("[{elapsed_precise}] {bar:40.cyan/blue} {msg}")
            .progress_chars("##-"),
    );

    let usernames = populate_users(&pool, row_count, &bar)?;

    let _ = populate_categories(&pool, "TestCategory", &bar)?;

    let survey_ids = populate_surveys(&pool, &usernames, row_count, &bar)?;
    let question_ids = populate_questions(&pool, &survey_ids, row_count, &bar)?;
    let choice_ids = populate_choices(&pool, &question_ids, row_count, &bar)?;
    populate_votes(&pool, &usernames, &choice_ids, &bar)?;
    bar.finish();
    println!("\r\n             🐦 Birdseed has Finished Seeding! 🐦\r\n",);
    Ok(())
}

// Kicks off populating all tables in main database and updating user
// with visual progress bar along the way
fn populate_icecream(row_count: u32) -> Result<(), Box<dyn Error>> {
    // get the base url and append it with the db name
    dotenv().ok();
    let base_url = env::var("PSQL_URL")?;
    env::set_var("DATABASE_URL", &format!("{}{}", base_url, "libellis"));

    let pool = generate_pool();
    println!("\r\n                  🐦 Seeding All Tables 🐦\r\n",);

    let bar = ProgressBar::new((row_count * 9) as u64);
    bar.set_style(
        ProgressStyle::default_bar()
            .template("[{elapsed_precise}] {bar:40.cyan/blue} {msg}")
            .progress_chars("##-"),
    );

    let usernames = populate_users(&pool, row_count, &bar)?;

    let _ = populate_categories(&pool, "food", &bar)?;

    let survey_id;

    // scoped so the pool connection gets dropped automatically
    {
        let pool = pool.clone();
        let conn = pool.get().unwrap();

        let survey_title = "What is your favorite icecream?";

        let cat = "food";

        let survey = create_survey(&conn, &usernames[0], &survey_title, cat);

        survey_id = survey.id;
    }

    let question_id;
    // question injection
    {
        let pool = pool.clone();
        let conn = pool.get().unwrap();

        let q_title = "What is your favorite icecream?";
        let q_type = "multiple".to_string();

        let question = create_question(&conn, survey_id, &q_type, &q_title);

        question_id = question.id;
    }

    let choices = vec!["Strawberry", "Vanilla", "Chocolate"];
    let choice_ids;

    // choice injection
    {
        let pool = pool.clone();
        let conn = pool.get().unwrap();

        choice_ids = choices
            .into_iter()
            .map(|choice| {
                let c_type = "text".to_string();
                let choice_struct = create_choice(&conn, question_id, &c_type, choice);
                choice_struct.id
            })
            .collect();
    }

    populate_icecream_votes(&pool, &usernames, &choice_ids, &bar)?;
    bar.finish();
    println!("\r\n             🐦 Birdseed has Finished Seeding! 🐦\r\n",);
    Ok(())
}

fn migrate(database: &str) -> Result<(), Box<dyn Error>> {
    // get the base url and append it with the db name
    dotenv().ok();
    let base_url = env::var("PSQL_URL")?;

    match database {
        "all" | "a" => {
            migrate_main(&base_url)?;
            migrate_test(&base_url)?;
        }
        "main" | "m" => migrate_main(&base_url)?,
        "test" | "t" => migrate_test(&base_url)?,
        _ => {
            return Err(io::Error::new(
                InvalidInput,
                "Invalid Database Type, choose 'main', 'test', or 'all'",
            )
            .into());
        }
    };

    Ok(())
}

fn migrate_main(base_url: &String) -> Result<(), Box<dyn Error>> {
    env::set_var("DATABASE_URL", &format!("{}{}", base_url, "libellis"));

    let conn = establish_connection();

    println!("\r\n                  🐦 Running Migrations on Main DB 🐦\r\n");
    embedded_migrations::run_with_output(&conn, &mut std::io::stdout())?;

    Ok(())
}

fn migrate_test(base_url: &String) -> Result<(), Box<dyn Error>> {
    env::set_var("DATABASE_URL", &format!("{}{}", base_url, "libellis_test"));

    let conn = establish_connection();

    println!("\r\n                  🐦 Running Migrations on Test DB 🐦\r\n");
    embedded_migrations::run_with_output(&conn, &mut std::io::stdout())?;

    Ok(())
}

// Clears all tables in appropriate order and increments a progress bar with
// custom start and completion messages
fn clear_all() -> Result<(), Box<dyn Error>> {
    use self::schema::*;

    // get the base url and append it with the db name
    dotenv().ok();
    let base_url = env::var("PSQL_URL")?;
    std::env::set_var("DATABASE_URL", &format!("{}{}", base_url, "libellis"));

    let conn = establish_connection();

    println!("\r\n                  🐦 Clearing all Tables 🐦\r\n");

    let bar = ProgressBar::new(7);
    bar.set_style(
        ProgressStyle::default_bar()
            .template("[{elapsed_precise}] {bar:40.cyan/blue} {msg}")
            .progress_chars("##-"),
    );

    diesel::delete(votes::table).execute(&conn)?;
    bar.inc(1);
    diesel::delete(fences::table).execute(&conn)?;
    bar.inc(1);
    diesel::delete(choices::table).execute(&conn)?;
    bar.inc(1);
    diesel::delete(questions::table).execute(&conn)?;
    bar.inc(1);
    diesel::delete(surveys::table).execute(&conn)?;
    bar.inc(1);
    diesel::delete(categories::table).execute(&conn)?;
    bar.inc(1);
    diesel::delete(users::table).execute(&conn)?;
    bar.inc(1);

    bar.finish();
    println!("\r\n                  🐦 All Tables Cleared! 🐦\r\n");

    Ok(())
}

// Drops all tables from libellis database
// Note that it's very intentional that we're not dealing with the result ->
// We don't care if a table doesn't exist, we simply want to attempt to drop
// ALL regardless so we are ready for a rebuild.  This takes care of situations
// where a user has manually deleted some but not all of their tables. Open a PR
// request if you have a better solution in mind.
#[allow(unused_must_use)]
fn drop_all(conn: &PgConnection) {
    let bar = ProgressBar::new(10);
    bar.set_style(
        ProgressStyle::default_bar()
            .template("[{elapsed_precise}] {bar:40.cyan/blue} {msg}")
            .progress_chars("##-"),
    );

    conn.execute("DROP TABLE fences cascade");
    bar.inc(1);
    conn.execute("DROP VIEW users_votes");
    bar.inc(1);
    conn.execute("DROP TABLE votes");
    bar.inc(1);
    conn.execute("DROP TABLE fences cascade");
    bar.inc(1);
    conn.execute("DROP TABLE choices");
    bar.inc(1);
    conn.execute("DROP TABLE questions");
    bar.inc(1);
    conn.execute("DROP TABLE surveys");
    bar.inc(1);
    conn.execute("DROP TABLE categories");
    bar.inc(1);
    conn.execute("DROP TABLE users");
    bar.inc(1);
    conn.execute("DROP TABLE __diesel_schema_migrations");
    bar.inc(1);
    bar.finish();
}

// Rebuilds all tables per most recent embedded diesel migrations
fn rebuild(database: &str) -> Result<(), Box<dyn Error>> {
    dotenv().ok();
    let base_url = env::var("PSQL_URL")?;

    match database {
        "all" | "a" => {
            rebuild_main(&base_url)?;
            rebuild_test(&base_url)?;
        }
        "main" | "m" => rebuild_main(&base_url)?,
        "test" | "t" => rebuild_test(&base_url)?,
        _ => {
            return Err(io::Error::new(
                InvalidInput,
                "Invalid Database Type, choose 'main', 'test', or 'all'",
            )
            .into());
        }
    };

    Ok(())
}

fn rebuild_main(base_url: &str) -> Result<(), Box<dyn Error>> {
    std::env::set_var("DATABASE_URL", &format!("{}{}", base_url, "libellis"));
    println!("\r\n                🐦 Connecting to Main DB 🐦\r\n");
    let conn = establish_connection();
    println!("\r\n                 🐦 Dropping all Tables 🐦\r\n");
    drop_all(&conn);
    println!("\r\n                  🐦 Running Migrations 🐦\r\n");
    embedded_migrations::run_with_output(&conn, &mut std::io::stdout())?;
    println!("\r\n              🐦 Tables Successfully Rebuilt! 🐦\r\n");
    Ok(())
}

fn rebuild_test(base_url: &str) -> Result<(), Box<dyn Error>> {
    std::env::set_var("DATABASE_URL", &format!("{}{}", base_url, "libellis_test"));
    println!("\r\n                🐦 Connecting to Test DB 🐦\r\n");
    let conn = establish_connection();
    println!("\r\n                 🐦 Dropping all Tables 🐦\r\n");
    drop_all(&conn);
    println!("\r\n                  🐦 Running Migrations 🐦\r\n");
    embedded_migrations::run_with_output(&conn, &mut std::io::stdout())?;
    println!("\r\n              🐦 Tables Successfully Rebuilt! 🐦\r\n");
    Ok(())
}

// Populates users table with row_count random users
fn populate_users(
    pool: &Pool,
    row_count: u32,
    bar: &ProgressBar,
) -> Result<Vec<String>, Box<dyn Error>> {
    bar.set_message(&format!("Seeding {} users", row_count));

    let usernames: Vec<String> = (0..row_count)
        .into_par_iter()
        .map(|_| {
            let pool = pool.clone();

            let conn = pool.get().unwrap();

            let user = format!(
                "{}{}",
                fake!(Internet.user_name),
                fake!(Number.between(90, 9999))
            );
            let pw = format!(
                "{}{}",
                fake!(Name.name),
                fake!(Number.between(10000, 99999))
            );
            let em = format!("{}@gmail.com", user);
            let first = format!("{}", fake!(Name.first_name));
            let last = format!("{}", fake!(Name.last_name));

            create_user(&conn, &user, &pw, &em, &first, &last);
            bar.inc(1);

            user
        })
        .collect();

    Ok(usernames)
}

// TODO: UPDATE THIS TO POPULATE RANDOM CHOICES
fn populate_categories(
    pool: &Pool,
    title: &str,
    bar: &ProgressBar,
) -> Result<String, Box<dyn Error>> {
    bar.set_message(&format!("Seeding 1 Test Category"));

    let pool = pool.clone();
    let conn = pool.get().unwrap();

    create_category(&conn, title);

    Ok(title.to_string())
}

// Populates surveys table with row_count random surveys making sure each survey is being created
// by an existing user
fn populate_surveys(
    pool: &Pool,
    authors: &Vec<String>,
    row_count: u32,
    bar: &ProgressBar,
) -> Result<Vec<i32>, Box<dyn Error>> {
    bar.set_message(&format!("Seeding {} surveys", row_count));

    let survey_ids: Vec<i32> = authors
        .par_iter()
        .map(|auth| {
            let pool = pool.clone();
            let conn = pool.get().unwrap();

            let survey_title = format!("{}", fake!(Lorem.sentence(4, 8)));

            // TODO: Change this later to not be a static category field
            let cat = "TestCategory";

            let survey = create_survey(&conn, &auth, &survey_title, cat);
            bar.inc(1);

            survey.id
        })
        .collect();

    Ok(survey_ids)
}

// Populates questions table with row_count random questions ensuring that each question relates to
// an existing survey
fn populate_questions(
    pool: &Pool,
    survey_ids: &Vec<i32>,
    row_count: u32,
    bar: &ProgressBar,
) -> Result<Vec<i32>, Box<dyn Error>> {
    bar.set_message(&format!("Seeding {} questions", row_count));

    let question_ids: Vec<i32> = survey_ids
        .par_iter()
        .map(|s_id| {
            let pool = pool.clone();
            let conn = pool.get().unwrap();

            let q_title = format!("{}", fake!(Lorem.sentence(3, 7)));
            let q_type = "multiple".to_string();
            let question = create_question(&conn, *s_id, &q_type, &q_title);
            bar.inc(1);

            question.id
        })
        .collect();

    Ok(question_ids)
}

// Populates choices table with row_count * 4 random choices ensuring that each question relates to
// an existing survey
fn populate_choices(
    pool: &Pool,
    question_ids: &Vec<i32>,
    row_count: u32,
    bar: &ProgressBar,
) -> Result<Vec<i32>, Box<dyn Error>> {
    bar.set_message(&format!("Seeding {} choices", (row_count * 4)));

    let choice_ids: Vec<i32> = question_ids
        .par_iter()
        .map(|q_id| {
            // For each question, inject 4 random text choices
            (0..4)
                .into_par_iter()
                .map(|_| {
                    let pool = pool.clone();
                    let conn = pool.get().unwrap();

                    let c_title = format!("{}", fake!(Lorem.sentence(1, 4)));
                    let c_type = "text".to_string();
                    let choice = create_choice(&conn, *q_id, &c_type, &c_title);
                    bar.inc(1);
                    choice.id
                })
                .collect()
        })
        .collect::<Vec<Vec<i32>>>()
        .concat();

    Ok(choice_ids)
}

// Populates the votes table with real votes from our newly inserted random users who vote on
// choices in a semi-randomish way (not that random really)
fn populate_votes(
    pool: &Pool,
    authors: &Vec<String>,
    choice_ids: &Vec<i32>,
    bar: &ProgressBar,
) -> Result<(), Box<dyn Error>> {
    bar.set_message(&format!("{} users are voting", (authors.len())));

    // Create vectors of idx and shuffle them
    let mut rng = thread_rng();
    let mut choice_idxs: Vec<usize> = (0..choice_ids.len()).collect();
    let choice_slice: &mut [usize] = &mut choice_idxs;
    let mut author_idxs: Vec<usize> = (0..authors.len()).collect();
    let author_slice: &mut [usize] = &mut author_idxs;
    choice_slice.shuffle(&mut rng);
    author_slice.shuffle(&mut rng);

    // For each round up randomize the choice and the author voting
    // on the choice
    author_slice.par_iter().enumerate().for_each(|(i, rand_i)| {
        let name = &authors[*rand_i];

        if i < authors.len() - 1 {
            (1..5 as usize).into_par_iter().for_each(|j| {
                let pool = pool.clone();
                let conn = pool.get().unwrap();

                let c_id = choice_ids[choice_slice[(i + 1) * j]];

                let geo_pnt: GeogPoint = gen_rand_geo();
                let geo_val = Point(vec![geo_pnt.x, geo_pnt.y]);

                let fence_tit = get_fence_by_coords(&conn, geo_val).unwrap();

                create_vote(&conn, c_id, name, 1, geo_pnt, &fence_tit);
                bar.inc(1);
            });
        }
    });

    Ok(())
}

#[derive(Copy, Clone, Debug)]
pub struct GeoBox {
    pub x_range: (f64, f64),
    pub y_range: (f64, f64),
}

use rand::Rng;

fn gen_rand_geo() -> GeogPoint {
    let mut rng = rand::thread_rng();
    let box1 = GeoBox {
        x_range: (-122.4378204345703, -122.40348815917969),
        y_range: (37.77831314799669, 37.80381638220768),
    };

    let box2 = GeoBox {
        x_range: (-122.50579833984375, -122.39250183105467),
        y_range: (37.74248523826606, 37.783740105227224),
    };

    let boxes: Vec<GeoBox> = vec![box1, box2];

    // generate random number between 0 and 1 and round to figure out which index to pick
    // then generate random ranges between the bounds for that box and return a new GeogPoint
    let index_choice = rng.gen::<f64>().round() as usize;
    let choosen_box = boxes[index_choice].clone();

    let mut rng1 = rand::thread_rng();
    let mut rng2 = rand::thread_rng();
    GeogPoint {
        x: rng1.gen_range(choosen_box.x_range.0, choosen_box.x_range.1),
        y: rng2.gen_range(choosen_box.y_range.0, choosen_box.y_range.1),
        srid: Some(4326),
    }
}

fn populate_icecream_votes(
    pool: &Pool,
    authors: &Vec<String>,
    choice_ids: &Vec<i32>,
    bar: &ProgressBar,
) -> Result<(), Box<dyn Error>> {
    bar.set_message(&format!("{} users are voting", (authors.len())));

    authors.par_iter().for_each(|author| {
        let mut rng = thread_rng();
        let pool = pool.clone();
        let conn = pool.get().unwrap();

        let c_id = choice_ids[rng.gen_range(0, 3) as usize];

        // placeholder - randomize later
        let geo_pnt: GeogPoint = gen_rand_geo();

        let geo_val = Point(vec![geo_pnt.x, geo_pnt.y]);

        let fence_tit = get_fence_by_coords(&conn, geo_val).unwrap();

        create_vote(&conn, c_id, author, 1, geo_pnt, &fence_tit);
        bar.inc(1);
    });

    Ok(())
}

fn get_fence_by_coords(conn: &PgConnection, coords: Value) -> Result<String, Box<dyn Error>> {
    use diesel::dsl::sql;
    use self::schema::fences::dsl::*;

    let geo_json = GeoJson::from(Geometry::new(coords));

    let where_str = format!("ST_Intersects(ST_GeomFromGeoJSON('{}'), geo)", geo_json.to_string());
    
    let fence: String = fences.select(title).filter(sql(&where_str)).first(conn)?;
    
    Ok(fence)
}

// Establishes a connection to the libellis postgres database on your machine, as specified by your
// DATABASE_URL environment variable. Returns a single PgConnection
fn establish_connection() -> PgConnection {
    dotenv().ok();

    let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");

    PgConnection::establish(&database_url).expect(&format!("Error connecting to {}", database_url))
}

// Establishes a connection to the libellis postgres database on your machine, as specified by your
// DATABASE_URL environment variable. Returns a Pool
fn generate_pool() -> Pool {
    dotenv().ok();

    let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");

    pg_pool::init(&database_url)
}

/**
 * The following series of functions are very simple - each one simply creates a single
 * user/survey/question/choice/vote
 */
fn create_user<'a>(
    conn: &PgConnection,
    user: &'a str,
    pw: &'a str,
    em: &'a str,
    first: &'a str,
    last: &'a str,
) -> User {
    use self::schema::users;

    let new_user = NewUser {
        username: user,
        password: pw,
        email: em,
        first_name: first,
        last_name: last,
        is_admin: false,
    };

    diesel::insert_into(users::table)
        .values(&new_user)
        .get_result(conn)
        .expect("Error saving new user")
}

fn create_survey<'a>(
    conn: &PgConnection,
    auth: &'a str,
    survey_title: &'a str,
    cat: &'a str,
) -> Survey {
    use self::schema::surveys;

    let new_survey = NewSurvey {
        author: auth,
        title: survey_title,
        published: true,
        category: cat,
    };

    diesel::insert_into(surveys::table)
        .values(&new_survey)
        .get_result(conn)
        .expect("Error saving new survey")
}

fn create_question<'a>(
    conn: &PgConnection,
    s_id: i32,
    q_type: &'a str,
    q_title: &'a str,
) -> Question {
    use self::schema::questions;

    let new_question = NewQuestion {
        survey_id: s_id,
        question_type: q_type,
        title: q_title,
    };

    diesel::insert_into(questions::table)
        .values(&new_question)
        .get_result(conn)
        .expect("Error saving new question")
}

fn create_choice<'a>(conn: &PgConnection, q_id: i32, c_type: &'a str, c_title: &'a str) -> Choice {
    use self::schema::choices;

    let new_choice = NewChoice {
        question_id: q_id,
        content_type: c_type,
        title: c_title,
    };

    diesel::insert_into(choices::table)
        .values(&new_choice)
        .get_result(conn)
        .expect("Error saving new choice")
}

fn create_vote<'a>(
    conn: &PgConnection,
    c_id: i32,
    name: &'a str,
    points: i32,
    geo_pnt: GeogPoint,
    fence_tit: &'a str,
) -> Vote {
    use self::schema::votes;

    let new_vote = NewVote {
        choice_id: c_id,
        username: name,
        score: points,
        geo: geo_pnt,
        fence_title: fence_tit,
    };

    diesel::insert_into(votes::table)
        .values(&new_vote)
        .get_result(conn)
        .expect("Error saving new vote")
}

fn create_category<'a>(conn: &PgConnection, title: &'a str) -> Category {
    use self::schema::categories;

    let new_category = NewCategory { title };

    diesel::insert_into(categories::table)
        .values(&new_category)
        .get_result(conn)
        .expect("Error saving new vote")
}