Ejemplo n.º 1
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 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();
        }
        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();
                }
            };
        }