private void MapOnMarkerDragEnd(object sender, GoogleMap.MarkerDragEndEventArgs e)
        {
            coords.Latitude  = e.Marker.Position.Latitude;
            coords.Longitude = e.Marker.Position.Longitude;

            // Setting new location coordinates once user drops marker
            var coordinates = coords.Latitude + "," + coords.Longitude;

            mDatabase.Child("tournaments").Child(tourneyID).Child("location").SetValueAsync(coordinates);
        }
Ejemplo n.º 2
0
        private async void saveData()
        {
            /*
             * UserViewModel newUser = new UserViewModel
             * {
             *  Email = auth.CurrentUser.Email,
             *  FirstName = firstName.Text.Trim(),
             *  LastName = lastName.Text.Trim(),
             *  City = City.Text.Trim(),
             *  Country = Country.Text.Trim(),
             *  Bio = Bio.Text.Trim()
             * };
             */

            //firebase = new FirebaseClient("https://fir-test-1bdb3.firebaseio.com/users/");
            //var item = firebase.Child("").PostAsync<UserViewModel>(newUser);
            DatabaseReference mDatabase = FirebaseDatabase.Instance.Reference;
            await mDatabase.Child("users").Child(userKey).Child("FirstName").SetValueAsync(firstName.Text.Trim());

            await mDatabase.Child("users").Child(userKey).Child("LastName").SetValueAsync(lastName.Text.Trim());

            await mDatabase.Child("users").Child(userKey).Child("City").SetValueAsync(City.Text.Trim());

            await mDatabase.Child("users").Child(userKey).Child("Country").SetValueAsync(Country.Text.Trim());

            await mDatabase.Child("users").Child(userKey).Child("Bio").SetValueAsync(Bio.Text.Trim());

            await mDatabase.Child("users").Child(userKey).Child("PhotoURL").SetValueAsync(PhotoURL);


            // SO MANY CHECKS LEFT HERE !!!!!!
        }
        protected override async void OnCreate(Bundle savedInstanceState)
        {
            string tourneyID = Intent.GetStringExtra("tourneyID") ?? "None";

            auth      = FirebaseAuth.GetInstance(MainActivity.app);
            mDatabase = FirebaseDatabase.Instance.Reference;

            base.OnCreate(savedInstanceState);

            // Loading tournaments
            var firebase = new FirebaseClient("https://fir-test-1bdb3.firebaseio.com/");
            var items    = await firebase
                           .Child("tournaments")
                           .OnceAsync <TournamentViewModel>();

            foreach (var item in items)
            {
                if (item.Object.TournamentID.Equals(tourneyID))
                {
                    query = item.Object;
                    break;
                }
            }



            SetContentView(Resource.Layout.ViewEventPage);

            // Adding Components
            TextView title      = FindViewById <TextView>(Resource.Id.tournamentTitle);
            TextView startDate  = FindViewById <TextView>(Resource.Id.startDateTitle);
            TextView finishDate = FindViewById <TextView>(Resource.Id.finishDateTitle);
            TextView awardMoney = FindViewById <TextView>(Resource.Id.awardMoneyTitle);
            TextView format     = FindViewById <TextView>(Resource.Id.formatTitle);

            Button location       = FindViewById <Button>(Resource.Id.location);
            Button adminProfile   = FindViewById <Button>(Resource.Id.adminProfileView);
            Button register       = FindViewById <Button>(Resource.Id.register);
            Button edit           = FindViewById <Button>(Resource.Id.edit);
            Button bracketURL     = FindViewById <Button>(Resource.Id.bracketLink);
            Button updateResult   = FindViewById <Button>(Resource.Id.updateResult);
            Button searchOpponent = FindViewById <Button>(Resource.Id.searchOpponentButton);
            Button endTournament  = FindViewById <Button>(Resource.Id.finishTournament);

            AutoCompleteTextView matchNumber        = FindViewById <AutoCompleteTextView>(Resource.Id.MatchNumberText);
            AutoCompleteTextView matchWinner        = FindViewById <AutoCompleteTextView>(Resource.Id.matchWinnerText);
            AutoCompleteTextView searchOpponentText = FindViewById <AutoCompleteTextView>(Resource.Id.searchOpponent);

            ImageView showCase    = FindViewById <ImageView>(Resource.Id.tourneyImageShowCaseEventPage);
            string    showCaseURL = "https://firebasestorage.googleapis.com/v0/b/fir-test-1bdb3.appspot.com/o/ShowCase.png?alt=media&token=f0c6e2e7-e9fc-46e8-a2ad-528ebf778aad";

            Glide.With(this).Load(showCaseURL).Apply(RequestOptions.CircleCropTransform()).Into(showCase);


            if (MainActivity.decision.Equals("Login as Admin"))
            {
                register.Enabled = false;
            }

            if (query.Finished.Equals("true"))
            {
                matchNumber.Enabled  = false;
                matchWinner.Enabled  = false;
                updateResult.Enabled = false;
            }

            if (!query.AdminID.Equals(auth.CurrentUser.Email))
            {
                edit.Enabled          = false;
                matchNumber.Enabled   = false;
                matchWinner.Enabled   = false;
                updateResult.Enabled  = false;
                endTournament.Enabled = false;
            }

            if (query.online.Equals("true"))
            {
                location.Enabled = false;
            }

            if (query.Live.Equals("false"))
            {
                bracketURL.Enabled   = false;
                matchNumber.Enabled  = false;
                matchWinner.Enabled  = false;
                updateResult.Enabled = false;
            }
            else
            {
                register.Enabled = false;
            }

            if (query.Paid.Equals("false"))
            {
                register.Text = "Register for Free";
            }
            else
            {
                register.Text = "Register for " + query.EntryFee + "¢";
            }



            title.Text      = query.Title ?? "";
            startDate.Text  = query.StartDate ?? "";
            finishDate.Text = query.FinishDate ?? "";
            awardMoney.Text = query.AwardMoney + "" ?? "";
            format.Text     = query.Format ?? "";

            endTournament.Click += async(sender, e) =>
            {
                if (query.Finished.Equals("true"))
                {
                    Toast.MakeText(ApplicationContext, "Tournament is already Over!", ToastLength.Short).Show();
                }
                else
                {
                    if (query.Live.Equals("true"))
                    {
                        await mDatabase.Child("tournaments").Child(tourneyID).Child("Finished").SetValueAsync("true");

                        Toast.MakeText(ApplicationContext, "Tournament Ended", ToastLength.Short).Show();
                    }
                    else
                    {
                        Toast.MakeText(ApplicationContext, "You cannot end a tournament before it goes live!", ToastLength.Short).Show();
                    }
                }
            };

            searchOpponent.Click += async(sender, e) =>
            {
                // Loading users' data for searching
                var users = await firebase.Child("users").OnceAsync <UserViewModel>();

                bool   found  = false;
                string userID = "";

                foreach (var user in users)
                {
                    if (user.Object.Email.Equals(searchOpponentText.Text.Trim().ToLower()))
                    {
                        found  = true;
                        userID = user.Object.Email;
                        break;
                    }
                }

                if (found)
                {
                    Intent viewProfileActivity = new Intent(Application.Context, typeof(ViewProfileActivity));
                    viewProfileActivity.PutExtra("toEmail", userID); // Recipient email
                    HomeActivity.fromHome = false;
                    StartActivity(viewProfileActivity);
                }
                else
                {
                    Toast.MakeText(ApplicationContext, "Invalid user", ToastLength.Short).Show();
                }
            };

            updateResult.Click += async(sender, e) =>
            {
                int  spo;
                bool validInputs = false;

                // Getting user input values

                int  matchNo;
                bool result = int.TryParse(matchNumber.Text, out matchNo);

                int  playerNo;
                bool result2 = int.TryParse(matchWinner.Text, out playerNo);

                if (result && result2)
                {
                    string url = "https://api.challonge.com/v1/tournaments/" + query.BracketID + "/matches.json?api_key=nzFuvS0FNlSVr7KWKdTpoCqP4EXhPAlyMccTfIyy";
                    // Create an HTTP web request using the URL:
                    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
                    request.ContentType = "application/json";
                    request.Method      = "GET";
                    request.Timeout     = 20200000;

                    // Send the request to the server and wait for the response:
                    using (WebResponse response = await request.GetResponseAsync())
                    {
                        // Get a stream representation of the HTTP web response:
                        using (Stream stream = response.GetResponseStream())
                        {
                            // Use this stream to build a JSON document object:
                            JsonValue jsonDoc = await Task.Run(() => JsonObject.Load(stream));

                            foreach (JsonValue abc in jsonDoc)
                            {
                                JsonValue match = abc["match"];

                                spo = match["suggested_play_order"];

                                if (spo == matchNo)
                                {
                                    id          = match["id"];
                                    validInputs = true;

                                    if (playerNo == 1)
                                    {
                                        matchWinnerID = match["player1_id"];
                                        matchScore    = "1-0";
                                    }
                                    else if (playerNo == 2)
                                    {
                                        matchWinnerID = match["player2_id"];
                                        matchScore    = "0-1";
                                    }
                                    else
                                    {
                                        validInputs = false;
                                    }

                                    break;
                                }
                            }
                        }
                    }

                    // Now updating the result of that particular match
                    if (validInputs)
                    {
                        url = "https://api.challonge.com/v1/tournaments/" + query.BracketID + "/matches/" + id + ".json?api_key=nzFuvS0FNlSVr7KWKdTpoCqP4EXhPAlyMccTfIyy&match[winner_id]=" + matchWinnerID + "&match[scores_csv]=" + matchScore;
                        // Create an HTTP web request using the URL:
                        request               = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
                        request.ContentType   = "application/json";
                        request.Method        = "PUT";
                        request.ContentLength = 0;
                        request.Timeout       = 20200000;

                        // Send the request to the server and wait for the response:
                        using (WebResponse response = await request.GetResponseAsync())
                        {
                            // Get a stream representation of the HTTP web response:
                            using (Stream stream = response.GetResponseStream())
                            {
                                // Use this stream to build a JSON document object:
                                JsonValue jsonDoc = await Task.Run(() => JsonObject.Load(stream));

                                Console.Out.WriteLine("Response: {0}", jsonDoc.ToString());
                            }
                        }
                    }
                    else
                    {
                        Toast.MakeText(ApplicationContext, "Either Match number or Player number is not valid. Try again.", ToastLength.Long).Show();
                    }
                }
                else
                {
                    Toast.MakeText(ApplicationContext, "Match Number and Player number must be whole numbers", ToastLength.Long).Show();
                }
            };

            bracketURL.Click += (sender, e) =>
            {
                Intent viewBracket = new Intent(Application.Context, typeof(ViewTournamentBracketActivity));
                viewBracket.PutExtra("url", query.BracketURL);
                StartActivity(viewBracket);
            };

            edit.Click += (sender, e) =>
            {
                Intent editTournament = new Intent(Application.Context, typeof(AddTournamentActivity));
                editTournament.PutExtra("tourneyID", tourneyID);
                StartActivity(editTournament);
            };

            location.Click += (sender, e) =>
            {
                Intent viewTournamentLocation = new Intent(Application.Context, typeof(ViewTournamentLocationActivity));
                viewTournamentLocation.PutExtra("coords", query.Location);
                StartActivity(viewTournamentLocation);
            };

            adminProfile.Click += (sender, e) =>
            {
                Intent viewProfileActivity = new Intent(Application.Context, typeof(ViewProfileActivity));
                viewProfileActivity.PutExtra("toEmail", query.AdminID); // Recipient email
                HomeActivity.fromHome = false;
                StartActivity(viewProfileActivity);
            };

            register.Click += async(sender, e) =>
            {
                string temp     = query.Participants;
                string entryFee = query.EntryFee;

                // Temp change here from null to ""
                if (temp == null)
                {
                    if (query.Paid.Equals("false"))
                    {
                        temp = "";

                        temp += auth.CurrentUser.Email;

                        await mDatabase.Child("tournaments").Child(tourneyID).Child("Participants").SetValueAsync(temp);

                        Toast.MakeText(ApplicationContext, "Registered", ToastLength.Long).Show();
                    }
                    else
                    {
                        // Render the view from the type generated from RazorView.cshtml
                        var model = new PaymentSendModel()
                        {
                            TournamentID = tourneyID, EntryFee = entryFee, NewParticipant = "true", Participants = "none", PlayerEmail = auth.CurrentUser.Email
                        };
                        //string query = "?tourneyID=" + tourneyID + "&entryFee=" + entryFee + "&NewParticipant=true&PlayerEmail=" + auth.CurrentUser.Email;
                        var template = new PaymentSendRazorView()
                        {
                            Model = model
                        };
                        var page = template.GenerateString();

                        // Load the rendered HTML into the view with a base URL
                        // that points to the root of the bundled Assets folder
                        // It is done in another activity
                        Intent makePaymentActivity = new Intent(Application.Context, typeof(MakePaymentActivity));
                        makePaymentActivity.PutExtra("page", page);
                        StartActivity(makePaymentActivity);
                    }
                }
                else
                {
                    bool registered = false;

                    string[] temps = temp.Split(',');

                    if (temps.Count() == int.Parse(query.ParticipantsLimit))
                    {
                        Toast.MakeText(ApplicationContext, "Registration is full!", ToastLength.Long).Show();
                    }
                    else
                    {
                        foreach (string item in temps)
                        {
                            if (item.Equals(auth.CurrentUser.Email))
                            {
                                registered = true;
                                Toast.MakeText(ApplicationContext, "Already Registered", ToastLength.Long).Show();
                                break;
                            }
                        }

                        if (!registered)
                        {
                            if (query.Paid.Equals("false"))
                            {
                                temp += "," + auth.CurrentUser.Email;

                                await mDatabase.Child("tournaments").Child(tourneyID).Child("Participants").SetValueAsync(temp);

                                Toast.MakeText(ApplicationContext, "Registered", ToastLength.Long).Show();
                            }
                            else
                            {
                                // Render the view from the type generated from RazorView.cshtml
                                var model = new PaymentSendModel()
                                {
                                    TournamentID = tourneyID, EntryFee = entryFee, NewParticipant = "false", Participants = temp, PlayerEmail = auth.CurrentUser.Email
                                };
                                //string query = "?tourneyID=" + tourneyID + "&entryFee=" + entryFee + "&NewParticipant=true&PlayerEmail=" + auth.CurrentUser.Email;
                                var template = new PaymentSendRazorView()
                                {
                                    Model = model
                                };
                                var page = template.GenerateString();

                                // Load the rendered HTML into the view with a base URL
                                // that points to the root of the bundled Assets folder
                                // It is done in another activity
                                Intent makePaymentActivity = new Intent(Application.Context, typeof(MakePaymentActivity));
                                makePaymentActivity.PutExtra("page", page);
                                StartActivity(makePaymentActivity);
                            }
                        }
                    }
                }


                /*
                 * if (query.Participants == null)
                 *  query.Participants = "";
                 *
                 * query.Participants += test + ",";
                 * db.Update(query);
                 * query = (from s in db.Table<TournamentViewModel>()
                 *       where s.TournamentID == tourneyID
                 *       select s).FirstOrDefault();
                 *
                 * Intent viewTournamentsActivity = new Intent(Application.Context, typeof(ViewTournamentsActivity));
                 * viewTournamentsActivity.PutExtra("email", test);
                 * viewTournamentsActivity.PutExtra("userType", userType);
                 * StartActivity(viewTournamentsActivity);
                 * Toast.MakeText(ApplicationContext, "Registered", ToastLength.Long).Show();
                 */
            };
        }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            // Getting current location
            fusedLocationProviderClient = LocationServices.GetFusedLocationProviderClient(this);

            Task.Run(GetLastLocationFromDevice);

            base.OnCreate(savedInstanceState);

            auth      = FirebaseAuth.GetInstance(MainActivity.app);
            mDatabase = FirebaseDatabase.Instance.Reference;

            tourneyID = Intent.GetStringExtra("tourneyID") ?? "None";

            SetContentView(Resource.Layout.AddLocation);

            // Adding location button
            Button currentLocationButton = FindViewById <Button>(Resource.Id.currentLocationButton);

            currentLocationButton.Click += (sender, e) =>
            {
                CameraPosition.Builder builder = CameraPosition.InvokeBuilder();
                builder.Target(coords);
                builder.Zoom(18);
                builder.Bearing(155);
                builder.Tilt(65);
                CameraPosition cameraPosition = builder.Build();
                CameraUpdate   cameraUpdate   = CameraUpdateFactory.NewCameraPosition(cameraPosition);
                if (_map != null)
                {
                    // Puttin a marker in this location for admin to move around
                    MarkerOptions tournamentLocationMarker = new MarkerOptions();
                    tournamentLocationMarker.SetPosition(coords);
                    tournamentLocationMarker.SetTitle("Tournament Location");
                    tournamentLocationMarker.SetIcon(BitmapDescriptorFactory.DefaultMarker(BitmapDescriptorFactory.HueCyan));
                    tournamentLocationMarker.Draggable(true);
                    _map.MarkerDragEnd += MapOnMarkerDragEnd;
                    _map.AddMarker(tournamentLocationMarker);

                    // Moving Camera
                    _map.AnimateCamera(CameraUpdateFactory.NewCameraPosition(cameraPosition));

                    // Setting current location as tournament location in case admin does not want to change
                    var coordinates = coords.Latitude + "," + coords.Longitude;
                    mDatabase.Child("tournaments").Child(tourneyID).Child("location").SetValueAsync(coordinates);

                    // Changing button text
                    currentLocationButton.Text = "Tournament Location";
                }
                else
                {
                    Toast.MakeText(ApplicationContext, "Wait for location to load..", ToastLength.Long);
                }
            };

            // Adding Save location button
            Button saveLocationButton = FindViewById <Button>(Resource.Id.saveLocationButton);

            saveLocationButton.Click += async(sender, e) =>
            {
                if (coords != null)
                {
                    await mDatabase.Child("tournaments").Child(tourneyID).Child("online").SetValueAsync("false");

                    // Going back to Tournament Main page
                    Intent addTournamentActivity = new Intent(Application.Context, typeof(AddTournamentActivity));
                    addTournamentActivity.PutExtra("tourneyID", tourneyID);
                    StartActivity(addTournamentActivity);
                    Finish();
                }
                else
                {
                    Toast.MakeText(ApplicationContext, "Load Current Location and move Marker First", ToastLength.Long);
                }
            };

            InitMapFragment();
        }
Ejemplo n.º 5
0
        protected override async void OnCreate(Bundle savedInstanceState)
        {
            auth      = FirebaseAuth.GetInstance(MainActivity.app);
            mDatabase = FirebaseDatabase.Instance.Reference;

            tourneyID = Intent.GetStringExtra("tourneyID") ?? "None"; // It will be initiated if existing tournament is being edited

            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.AddTournament);

            // Adding Components
            Button   addTournament    = FindViewById <Button>(Resource.Id.addTournamentInfo);
            Button   addLocation      = FindViewById <Button>(Resource.Id.addLocation);
            CheckBox LANEvent         = FindViewById <CheckBox>(Resource.Id.LANEvent);
            Button   saveInfoButton   = FindViewById <Button>(Resource.Id.saveInfo);
            Button   cancelInfoButton = FindViewById <Button>(Resource.Id.cancelInfo);
            Button   liveButton       = FindViewById <Button>(Resource.Id.tournamentLiveButton);
            Button   noOfParticipants = FindViewById <Button>(Resource.Id.participantsNumberTourneyPage);

            cancelInfoButton.Text    = "Delete";
            noOfParticipants.Enabled = false;

            if (tourneyID.Equals("None")) // New tournament creation
            {
                LANEvent.Checked    = false;
                addLocation.Enabled = false;
                // tourneyID = Guid.NewGuid().ToString();

                var firebase = new FirebaseClient("https://fir-test-1bdb3.firebaseio.com/");
                var item     = await firebase.Child("tournaments")
                               .PostAsync <TournamentViewModel>(new TournamentViewModel
                {
                    AdminID      = auth.CurrentUser.Email,
                    TournamentID = "",
                    online       = "true",
                    Format       = "Knockout",
                    Live         = "false", // shows that is is not published yet
                    Description  = "",
                    Game         = "Game not set yet",
                    Finished     = "false"
                });

                await mDatabase.Child("tournaments").Child(item.Key).Child("TournamentID").SetValueAsync(item.Key);

                tourneyID = item.Key;
            }
            else
            {
                FirebaseClient firebase = new FirebaseClient("https://fir-test-1bdb3.firebaseio.com/tournaments/");
                var            items    = await firebase
                                          .Child("")
                                          .OnceAsync <TournamentViewModel>();

                foreach (var item in items)
                {
                    if (item.Key.Equals(tourneyID))
                    {
                        if (item.Object.online.Equals("true"))
                        {
                            addLocation.Enabled = false;
                            LANEvent.Checked    = false;
                        }
                        if (item.Object.Live.Equals("true"))
                        {
                            addLocation.Enabled   = false;
                            LANEvent.Enabled      = false;
                            addTournament.Enabled = false;
                        }

                        int  number;
                        bool result = int.TryParse(item.Object.ParticipantsLimit, out number);

                        if (result)
                        {
                            if (item.Object.Participants != null)
                            {
                                players = item.Object.Participants.Split(',');
                                noOfParticipants.Text = "Registered: " + (players.Count()) + "/" + number;
                                tourneyTitle          = item.Object.Title;

                                if (players.Count() != number)
                                {
                                    liveButton.Enabled = false;
                                }
                            }
                            else
                            {
                                noOfParticipants.Text = "Registered: " + "0/" + number;
                                liveButton.Enabled    = false;
                            }
                        }
                        else
                        {
                            liveButton.Enabled = false;
                        }

                        break;
                    }
                }
            }


            liveButton.Click += async(sender, e) =>
            {
                await mDatabase.Child("tournaments").Child(tourneyID).Child("Live").SetValueAsync("true");

                Toast.MakeText(ApplicationContext, "Tournament is now live! You cannot change any info now.", ToastLength.Long).Show();
                addLocation.Enabled   = false;
                LANEvent.Enabled      = false;
                addTournament.Enabled = false;

                // 1: GENERATE BRACKET WHEN TOURNAMENT GOES LIVE HERE!!
                var url = "https://api.challonge.com/v1/tournaments.json?api_key=nzFuvS0FNlSVr7KWKdTpoCqP4EXhPAlyMccTfIyy&tournament[name]=" + tourneyTitle.Trim() + "&tournament[url]=" + tourneyTitle.Trim() + "_" + tourneyTitle.Trim() + "UltimateESports" + "&tournament[open_signup]=false&tournament[description]=" + "To be added here. This space is for rules" + "&tournament[show_rounds]=true&tournament[signup_cap]=" + players.Count();

                // Create an HTTP web request using the URL:
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
                request.ContentType   = "application/json";
                request.Method        = "POST";
                request.ContentLength = 0;
                request.Timeout       = 300000;

                // For use in next function
                string urlFull;

                // Send the request to the server and wait for the response:
                using (WebResponse response = await request.GetResponseAsync())
                {
                    // Get a stream representation of the HTTP web response:
                    using (Stream stream = response.GetResponseStream())
                    {
                        // Use this stream to build a JSON document object:
                        JsonValue jsonDoc = await Task.Run(() => JsonObject.Load(stream));

                        //JsonValue a = jsonDoc[0];

                        JsonValue tourney = jsonDoc["tournament"];

                        string BracketID = tourney["full_challonge_url"];
                        urlFull = tourney["url"];

                        await mDatabase.Child("tournaments").Child(tourneyID).Child("BracketID").SetValueAsync(urlFull);

                        await mDatabase.Child("tournaments").Child(tourneyID).Child("BracketURL").SetValueAsync(BracketID);


                        //Console.Out.WriteLine("Response: {0}", jsonDoc.ToString());
                    }
                }

                // Add Players to the bracket
                foreach (var name in players)
                {
                    string addParticipant = "https://api.challonge.com/v1/tournaments/" + urlFull + "/participants.json?participant[name]=" + name + "&api_key=nzFuvS0FNlSVr7KWKdTpoCqP4EXhPAlyMccTfIyy";
                    request               = (HttpWebRequest)HttpWebRequest.Create(new Uri(addParticipant));
                    request.ContentType   = "application/json";
                    request.Method        = "POST";
                    request.ContentLength = 0;

                    using (WebResponse response = await request.GetResponseAsync())
                    {
                        // Get a stream representation of the HTTP web response:
                        using (Stream stream = response.GetResponseStream())
                        {
                            // Use this stream to build a JSON document object:
                            JsonValue jsonDoc = await Task.Run(() => JsonObject.Load(stream));

                            Console.Out.WriteLine("Response: {0}", jsonDoc.ToString());
                        }
                    }
                }

                // Starting the tournament
                url = "https://api.challonge.com/v1/tournaments/" + urlFull + "/start.json?api_key=nzFuvS0FNlSVr7KWKdTpoCqP4EXhPAlyMccTfIyy";

                request               = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
                request.ContentType   = "application/json";
                request.Method        = "POST";
                request.ContentLength = 0;

                using (WebResponse response = await request.GetResponseAsync())
                {
                    // Get a stream representation of the HTTP web response:
                    using (Stream stream = response.GetResponseStream())
                    {
                        // Use this stream to build a JSON document object:
                        JsonValue jsonDoc = await Task.Run(() => JsonObject.Load(stream));

                        Console.Out.WriteLine("Response: {0}", jsonDoc.ToString());
                    }
                }

                // 2: SEND MESSAGE TO ALL PARTICIPANTS FOR TOURNAMENT START !!
                var firebase = new FirebaseClient("https://fir-test-1bdb3.firebaseio.com/");
                foreach (var name in players)
                {
                    string message = tourneyTitle + "has just started.";

                    await firebase.Child("messages")
                    .PostAsync <MessageViewModel>(new MessageViewModel
                    {
                        ToEmail   = name,
                        FromEmail = auth.CurrentUser.Email,
                        Body      = message,
                        Timestamp = DateTime.Now.ToString()
                    });
                }
            };

            cancelInfoButton.Click += async(sender, e) =>
            {
                // Heading to Home Page
                var homeActivity = new Intent(Application.Context, typeof(HomeActivity));
                await mDatabase.Child("tournaments").Child(tourneyID).RemoveValueAsync();

                StartActivity(homeActivity);
                Finish();
            };

            saveInfoButton.Click += (sender, e) =>
            {
                // Heading to Home Page
                var homeActivity = new Intent(Application.Context, typeof(HomeActivity));
                StartActivity(homeActivity);
                Finish();
            };

            // Button actions
            addTournament.Click += (sender, e) =>
            {
                Intent addTournamentInfoActivity = new Intent(Application.Context, typeof(AddTournamentInfoActivity));
                addTournamentInfoActivity.PutExtra("tourneyID", tourneyID);
                StartActivity(addTournamentInfoActivity);
            };

            addLocation.Click += (sender, e) =>
            {
                // setting tournament as LAN

                Intent addLocationActivity = new Intent(Application.Context, typeof(AddLocationActivity));
                addLocationActivity.PutExtra("tourneyID", tourneyID);
                StartActivity(addLocationActivity);
            };

            // Checkbox action
            LANEvent.Click += async(sender, e) =>
            {
                if (LANEvent.Checked)
                {
                    addLocation.Enabled = true;
                    await mDatabase.Child("tournaments").Child(tourneyID).Child("online").SetValueAsync("false");
                }
                else
                {
                    addLocation.Enabled = false;
                    await mDatabase.Child("tournaments").Child(tourneyID).Child("online").SetValueAsync("true");
                }
            };
        }
        protected override async void OnCreate(Bundle savedInstanceState)
        {
            mDatabase = FirebaseDatabase.Instance.Reference;

            tourneyID = Intent.GetStringExtra("tourneyID") ?? "None";

            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.AddTournamentInfo);

            // Adding Components
            AutoCompleteTextView tournamentTitleText = FindViewById <AutoCompleteTextView>(Resource.Id.tournamentTitleText);
            AutoCompleteTextView awardMoney          = FindViewById <AutoCompleteTextView>(Resource.Id.awardMoneyText);
            AutoCompleteTextView participantsLimit   = FindViewById <AutoCompleteTextView>(Resource.Id.participantsLimitText);
            AutoCompleteTextView entryFee            = FindViewById <AutoCompleteTextView>(Resource.Id.entryFeeText);
            AutoCompleteTextView gameTitle           = FindViewById <AutoCompleteTextView>(Resource.Id.gameTitleText);
            AutoCompleteTextView description         = FindViewById <AutoCompleteTextView>(Resource.Id.descriptionText);
            RadioButton          knockout            = FindViewById <RadioButton>(Resource.Id.knockout);
            //RadioButton doubleEliminationKnockout = FindViewById<RadioButton>(Resource.Id.doubleEliminationKnockout);
            Button    saveTournamentInfoButton = FindViewById <Button>(Resource.Id.tournamentInfoSaveButton);
            Button    startDateButton          = FindViewById <Button>(Resource.Id.startDateButton);
            Button    finishDateButton         = FindViewById <Button>(Resource.Id.finishDateButton);
            ImageView showCase = FindViewById <ImageView>(Resource.Id.tourneyImageShowCase);

            string showCaseURL = "https://firebasestorage.googleapis.com/v0/b/fir-test-1bdb3.appspot.com/o/ShowCase.png?alt=media&token=f0c6e2e7-e9fc-46e8-a2ad-528ebf778aad";

            Glide.With(this).Load(showCaseURL).Apply(RequestOptions.CircleCropTransform()).Into(showCase);

            // Loading data from DB

            FirebaseClient firebase = new FirebaseClient("https://fir-test-1bdb3.firebaseio.com/tournaments/");
            var            items    = await firebase
                                      .Child("")
                                      .OnceAsync <TournamentViewModel>();

            foreach (var item in items)
            {
                if (item.Key.Equals(tourneyID))
                {
                    tournamentTitleText.Text = item.Object.Title ?? "";
                    startDateButton.Text     = item.Object.StartDate ?? "Start Date";
                    finishDateButton.Text    = item.Object.FinishDate ?? "Finish Date";
                    awardMoney.Text          = item.Object.AwardMoney + "" ?? "";
                    participantsLimit.Text   = item.Object.ParticipantsLimit ?? "";
                    entryFee.Text            = item.Object.EntryFee ?? "0";
                    gameTitle.Text           = item.Object.Game ?? "";
                    description.Text         = item.Object.Description ?? "";

                    //if (item.Object.Format.Equals("Double Elimination Knockout"))
                    //{
                    //     doubleEliminationKnockout.Checked = true;
                    //     tourneyFormat = "Double Elimination Knockout";
                    //}
                    if (item.Object.Format.Equals("Knockout"))
                    {
                        knockout.Checked = true;
                        tourneyFormat    = "Knockout";
                    }

                    break;
                }
            }

            startDateButton.Click += (sender, e) =>
            {
                DatePickerFragment frag = DatePickerFragment.NewInstance(delegate(DateTime time)
                {
                    startDateButton.Text = time.ToLongDateString();
                });
                frag.Show(FragmentManager, DatePickerFragment.TAG);
            };

            finishDateButton.Click += (sender, e) =>
            {
                DatePickerFragment frag = DatePickerFragment.NewInstance(delegate(DateTime time)
                {
                    finishDateButton.Text = time.ToLongDateString();
                });
                frag.Show(FragmentManager, DatePickerFragment.TAG);
            };

            async void RadioButtonClickAsync(object sender, EventArgs e)
            {
                RadioButton rb = (RadioButton)sender;

                tourneyFormat = rb.Text;
                await mDatabase.Child("tournaments").Child(tourneyID).Child("Format").SetValueAsync(rb.Text);
            }

            knockout.Click += RadioButtonClickAsync;
            //doubleEliminationKnockout.Click += RadioButtonClickAsync;

            saveTournamentInfoButton.Click += async(sender, e) =>
            {
                if (gameTitle.Text.Equals(string.Empty) || tournamentTitleText.Equals(string.Empty) || startDateButton.Text.Equals("Start Date") || finishDateButton.Text.Equals("Finish Date") || awardMoney.Equals(""))
                {
                    Toast.MakeText(ApplicationContext, "Enter data in all fields first", ToastLength.Long).Show();
                }
                else
                {
                    string titleTemp = tournamentTitleText.Text.Replace(' ', '_');
                    titleTemp = tournamentTitleText.Text.Replace('-', '_');
                    titleTemp = tournamentTitleText.Text.Replace('.', '_');
                    await mDatabase.Child("tournaments").Child(tourneyID).Child("Title").SetValueAsync(titleTemp);

                    await mDatabase.Child("tournaments").Child(tourneyID).Child("StartDate").SetValueAsync(startDateButton.Text);

                    await mDatabase.Child("tournaments").Child(tourneyID).Child("FinishDate").SetValueAsync(finishDateButton.Text);

                    await mDatabase.Child("tournaments").Child(tourneyID).Child("AwardMoney").SetValueAsync(awardMoney.Text);

                    await mDatabase.Child("tournaments").Child(tourneyID).Child("Game").SetValueAsync(gameTitle.Text.ToUpper());

                    await mDatabase.Child("tournaments").Child(tourneyID).Child("Description").SetValueAsync(description.Text);



                    // Inserting Participants limit if it meets certain conditions
                    int  limit;
                    bool result = int.TryParse(participantsLimit.Text, out limit);
                    if (result)
                    {
                        if (limit > 3 && limit < 33)
                        {
                            await mDatabase.Child("tournaments").Child(tourneyID).Child("ParticipantsLimit").SetValueAsync(participantsLimit.Text);
                        }
                        else
                        {
                            await mDatabase.Child("tournaments").Child(tourneyID).Child("ParticipantsLimit").SetValueAsync("6");

                            Toast.MakeText(ApplicationContext, "Limit should be above 3 or less than 33, so set to 6", ToastLength.Long).Show();
                        }
                    } // ELSE statement if number is not correct then set it to 6 by default
                    else
                    {
                        await mDatabase.Child("tournaments").Child(tourneyID).Child("ParticipantsLimit").SetValueAsync("6");

                        Toast.MakeText(ApplicationContext, "Invalid participants limit, set to 6 automatically", ToastLength.Long).Show();
                    }

                    // Checking and inserting the entry fee
                    int entryFeeNumber;
                    result = int.TryParse(entryFee.Text, out entryFeeNumber);
                    if (result)
                    {
                        if (entryFeeNumber == 0)
                        {
                            await mDatabase.Child("tournaments").Child(tourneyID).Child("EntryFee").SetValueAsync(entryFee.Text);

                            await mDatabase.Child("tournaments").Child(tourneyID).Child("Paid").SetValueAsync("false");
                        }
                        else
                        {
                            await mDatabase.Child("tournaments").Child(tourneyID).Child("EntryFee").SetValueAsync(entryFee.Text);

                            await mDatabase.Child("tournaments").Child(tourneyID).Child("Paid").SetValueAsync("true");
                        }
                    }
                    else
                    {
                        await mDatabase.Child("tournaments").Child(tourneyID).Child("EntryFee").SetValueAsync("0");

                        await mDatabase.Child("tournaments").Child(tourneyID).Child("Paid").SetValueAsync("false");

                        Toast.MakeText(ApplicationContext, "Entered Entry Fee number was invalid so it is set to 0 and Free", ToastLength.Long).Show();
                    }


                    // Going back to Tournament Main page
                    Intent addTournamentActivity = new Intent(Application.Context, typeof(AddTournamentActivity));
                    addTournamentActivity.PutExtra("tourneyID", tourneyID);
                    StartActivity(addTournamentActivity);
                    Finish();
                }
            };
        }