private async void insertIntoDB()
        {
            UserViewModel newUser = new UserViewModel
            {
                Email     = auth.CurrentUser.Email,
                FirstName = "",
                LastName  = "",
                Bio       = "",
                City      = "",
                Country   = ""
            };

            var firebase = new FirebaseClient("https://fir-test-1bdb3.firebaseio.com/users/");
            //firebase.Child("users");
            var item = await firebase.Child("").PostAsync <UserViewModel>(newUser);
        }
        private async void loadData()
        {
            circular_progress.Visibility = ViewStates.Visible;

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

            foreach (var item in items)
            {
                data.Text += item.Key + "\n" + item.Object.name + "\n" + item.Object.email + "\n\n";
            }

            circular_progress.Visibility = ViewStates.Invisible;
        }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            auth = FirebaseAuth.GetInstance(MainActivity.app);

            SetContentView(Resource.Layout.PublishPost);

            // Adding components
            EditText socialPostBody = FindViewById <EditText>(Resource.Id.socialPostBodyText);
            Button   publishButton  = FindViewById <Button>(Resource.Id.publishPostButton);

            circular_progress = FindViewById <ProgressBar>(Resource.Id.circularProgressPublishPost);

            publishButton.Click += async(sender, e) =>
            {
                if (socialPostBody.Text != string.Empty)
                {
                    circular_progress.Visibility = ViewStates.Visible;
                    var firebase = new FirebaseClient("https://fir-test-1bdb3.firebaseio.com/");
                    var item     = await firebase.Child("socialPosts")
                                   .PostAsync <SocialPostViewModel>(new SocialPostViewModel
                    {
                        Email        = auth.CurrentUser.Email,
                        Body         = socialPostBody.Text.Trim(),
                        SocialPostID = Guid.NewGuid().ToString(),
                        TimeStamp    = DateTime.Now.ToString()
                    });

                    socialPostBody.Text          = "";
                    circular_progress.Visibility = ViewStates.Invisible;
                    Toast.MakeText(ApplicationContext, "Published", ToastLength.Long).Show();
                }
                else
                {
                    Toast.MakeText(ApplicationContext, "Write something first", ToastLength.Long).Show();
                }
            };
        }
Exemple #4
0
        protected override async void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.ViewSocialFeed);

            auth = FirebaseAuth.GetInstance(MainActivity.app);

            // Adding views
            Button    timeStamp      = FindViewById <Button>(Resource.Id.timeStampSocialFeed);
            ImageView profilePicture = FindViewById <ImageView>(Resource.Id.profilePictureSocialFeed);
            Button    name           = FindViewById <Button>(Resource.Id.nameSocialFeed);
            Button    postBody       = FindViewById <Button>(Resource.Id.SocialFeedPostBody);
            Button    commentBody    = FindViewById <Button>(Resource.Id.SocialFeedCommentBody);
            Button    next           = FindViewById <Button>(Resource.Id.nextPost);
            Button    previous       = FindViewById <Button>(Resource.Id.previousPost);
            EditText  commentText    = FindViewById <EditText>(Resource.Id.CommentBodySocialFeed);
            Button    reply          = FindViewById <Button>(Resource.Id.commentButton);

            circular_progress = FindViewById <ProgressBar>(Resource.Id.circularProgressSocialFeed);

            timeStamp.Enabled   = false;
            name.Enabled        = false;
            postBody.Enabled    = false;
            commentBody.Enabled = false;

            circular_progress.Visibility = ViewStates.Visible;
            // Loading Social Posts from DB
            var firebase = new FirebaseClient("https://fir-test-1bdb3.firebaseio.com/");
            var query    = await firebase
                           .Child("socialPosts")
                           .OnceAsync <SocialPostViewModel>();

            //query.Reverse();

            List <SocialPostViewModel> posts = new List <SocialPostViewModel>();

            foreach (var item in query)
            {
                posts.Add(item.Object);
            }

            posts.Reverse();

            // Loading users' data to get profile pictures
            var users = await firebase.Child("users").OnceAsync <UserViewModel>();

            // Getting comments from DB
            firebase = new FirebaseClient("https://fir-test-1bdb3.firebaseio.com/");
            var comments = await firebase
                           .Child("comments")
                           .OnceAsync <CommentViewModel>();

            //comments.Reverse();

            List <CommentViewModel> commentsList = new List <CommentViewModel>();

            foreach (var item in comments)
            {
                commentsList.Add(item.Object);
            }



            int postNumber = 0; // To keep track

            // Loading first post into views
            timeStamp.Text = posts[postNumber].TimeStamp;
            //name.Text = posts[postNumber].Email;

            foreach (var item in users)
            {
                if (item.Object.Email.Equals(posts[postNumber].Email))
                {
                    if (!item.Object.PhotoURL.Equals(string.Empty))
                    {
                        Glide.With(this).Load(item.Object.PhotoURL).Apply(RequestOptions.CircleCropTransform()).Into(profilePicture);
                    }
                    name.Text = item.Object.FirstName + " " + item.Object.LastName ?? "";
                }
            }

            postBody.Text = posts[postNumber].Body;

            string commentTextTemp = "Comments:\n";
            int    commentCounter  = 0;

            // Filtering
            foreach (var item in commentsList)
            {
                if (item.SocialPostID.Equals(posts[postNumber].SocialPostID))
                {
                    commentCounter++;
                    commentTextTemp += "\n" + item.Email + ":\n" + " - " + item.Body + "\n";
                }
            }
            // Done getting comments


            if (commentCounter > 0)
            {
                commentBody.Text = commentTextTemp;
            }
            else
            {
                commentBody.Text += "\nNo Comments Yet";
            }

            circular_progress.Visibility = ViewStates.Invisible;

            next.Click += (sender, e) =>
            {
                if (query.Count() - 1 == postNumber)
                {
                    // No new posts
                    Toast.MakeText(ApplicationContext, "No more posts", ToastLength.Short).Show();
                }
                else
                {
                    circular_progress.Visibility = ViewStates.Visible;

                    postNumber++;

                    timeStamp.Text = posts[postNumber].TimeStamp;
                    //name.Text = posts[postNumber].Email;

                    foreach (var item in users)
                    {
                        if (item.Object.Email.Equals(posts[postNumber].Email))
                        {
                            if (!item.Object.PhotoURL.Equals(string.Empty))
                            {
                                Glide.With(this).Load(item.Object.PhotoURL).Apply(RequestOptions.CircleCropTransform()).Into(profilePicture);
                            }
                            name.Text = item.Object.FirstName + " " + item.Object.LastName ?? "";
                        }
                    }

                    postBody.Text = posts[postNumber].Body;

                    commentTextTemp = "Comments:\n";

                    commentCounter = 0;
                    // Filtering
                    foreach (var item in commentsList)
                    {
                        if (item.SocialPostID.Equals(posts[postNumber].SocialPostID))
                        {
                            commentCounter++;
                            commentTextTemp += "\n" + item.Email + ":\n" + " - " + item.Body + "\n";
                        }
                    }
                    // Done getting comments


                    if (commentCounter > 0)
                    {
                        commentBody.Text = commentTextTemp;
                    }
                    else
                    {
                        commentBody.Text  = "Comments:\n";
                        commentBody.Text += "\nNo Comments Yet";
                    }

                    circular_progress.Visibility = ViewStates.Invisible;
                }
            };

            previous.Click += (sender, e) =>
            {
                if (0 == postNumber)
                {
                    // No new posts
                    Toast.MakeText(ApplicationContext, "No more posts", ToastLength.Short).Show();
                }
                else
                {
                    circular_progress.Visibility = ViewStates.Visible;

                    postNumber--;

                    timeStamp.Text = posts[postNumber].TimeStamp;
                    name.Text      = posts[postNumber].Email;

                    foreach (var item in users)
                    {
                        if (item.Object.Email.Equals(posts[postNumber].Email))
                        {
                            if (!item.Object.PhotoURL.Equals(string.Empty))
                            {
                                Glide.With(this).Load(item.Object.PhotoURL).Apply(RequestOptions.CircleCropTransform()).Into(profilePicture);
                            }
                            name.Text = item.Object.FirstName + " " + item.Object.LastName ?? "";
                        }
                    }

                    postBody.Text = posts[postNumber].Body;

                    commentTextTemp = "Comments:\n";

                    commentCounter = 0;
                    // Filtering
                    foreach (var item in commentsList)
                    {
                        if (item.SocialPostID.Equals(posts[postNumber].SocialPostID))
                        {
                            commentCounter++;
                            commentTextTemp += "\n" + item.Email + ":\n" + " - " + item.Body + "\n";
                        }
                    }
                    // Done getting comments


                    if (commentCounter > 0)
                    {
                        commentBody.Text = commentTextTemp;
                    }
                    else
                    {
                        commentBody.Text  = "Comments:\n";
                        commentBody.Text += "\nNo Comments Yet";
                    }

                    circular_progress.Visibility = ViewStates.Invisible;
                }
            };

            reply.Click += async(sender, e) =>
            {
                if (commentText.Text != String.Empty)
                {
                    firebase = new FirebaseClient("https://fir-test-1bdb3.firebaseio.com/");
                    var item = await firebase.Child("comments")
                               .PostAsync <CommentViewModel>(new CommentViewModel
                    {
                        Email        = auth.CurrentUser.Email,
                        Body         = commentText.Text.Trim(),
                        SocialPostID = posts[postNumber].SocialPostID
                    });

                    commentText.Text = "";

                    Toast.MakeText(ApplicationContext, "Published", ToastLength.Short).Show();
                }
                else
                {
                    Toast.MakeText(ApplicationContext, "Enter a comment first", ToastLength.Long).Show();
                }
            };
        }
        protected override async void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            auth      = FirebaseAuth.GetInstance(MainActivity.app);
            fromEmail = auth.CurrentUser.Email; // Loading email of person opening this profile

            SetContentView(Resource.Layout.ViewProfile);

            // Adding components
            ImageView profilePicture    = FindViewById <ImageView>(Resource.Id.profilePicture);
            Button    sendMessageButton = FindViewById <Button>(Resource.Id.sendMessage);
            TextView  name              = FindViewById <TextView>(Resource.Id.name);
            TextView  location          = FindViewById <TextView>(Resource.Id.location);
            TextView  bio               = FindViewById <TextView>(Resource.Id.bio);
            TextView  email             = FindViewById <TextView>(Resource.Id.type);
            TextView  gamerTagsListText = FindViewById <TextView>(Resource.Id.gamerTagsListText);
            Button    gamerTagsList     = FindViewById <Button>(Resource.Id.gamerTagsList);
            // A button for Organaized tourneys here
            // A button for participated tourneys here
            GridLayout parent = FindViewById <GridLayout>(Resource.Id.gridLayoutAdminProfile);

            circular_progress = FindViewById <ProgressBar>(Resource.Id.circularProgressProfile);


            if (HomeActivity.fromHome)
            {
                toEmail = fromEmail;
                sendMessageButton.Enabled = false;
            }
            else
            {
                // bring toEmail in the intent extra here when someone else is visiting
                // Then toEmail and fromEmail will be different, for messageSend activity
                toEmail = Intent.GetStringExtra("toEmail") ?? "None";
            }


            circular_progress.Visibility = ViewStates.Visible;
            firebase = new FirebaseClient("https://fir-test-1bdb3.firebaseio.com/");
            var items = await firebase
                        .Child("users")
                        .OnceAsync <UserViewModel>();



            foreach (var item in items)
            {
                if (item.Object.Email.Equals(toEmail))
                {
                    name.Text     = item.Object.FirstName + " " + item.Object.LastName ?? "";
                    bio.Text      = item.Object.Bio ?? "";
                    location.Text = item.Object.City + ", " + item.Object.Country ?? "";
                    email.Text    = toEmail ?? "";

                    if (!item.Object.PhotoURL.Equals(string.Empty))
                    {
                        Glide.With(this).Load(item.Object.PhotoURL).Into(profilePicture);
                    }


                    break;
                }
            }
            circular_progress.Visibility = ViewStates.Invisible;

            // sendMessage Click method here
            sendMessageButton.Click += (sender, e) =>
            {
                HomeActivity.fromHome = false;
                Intent sendMessageActivity = new Intent(Application.Context, typeof(MessageSendActivity));
                sendMessageActivity.PutExtra("toEmail", toEmail);
                StartActivity(sendMessageActivity);
            };

            // Gamer Tags button
            gamerTagsList.Click += async(sender, e) =>
            {
                circular_progress.Visibility = ViewStates.Visible;
                var tags = await firebase
                           .Child("gamerTags")
                           .OnceAsync <GameTagViewModel>();

                string temp  = "";
                int    count = 1;

                foreach (var tag in tags)
                {
                    if (tag.Object.Email.Equals(toEmail))
                    {
                        temp += "#" + count + ": " + tag.Object.GameTitle + " (" + tag.Object.Platform + "): " + tag.Object.GamerTag + "\n";
                        count++;
                    }
                }
                gamerTagsListText.Text       = temp.Substring(0, temp.Length - 1);
                circular_progress.Visibility = ViewStates.Invisible;
            };
        }
Exemple #6
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            auth = FirebaseAuth.GetInstance(MainActivity.app);

            SetContentView(Resource.Layout.MessageSend);

            EditText recipient = FindViewById <EditText>(Resource.Id.recipient);
            EditText message   = FindViewById <EditText>(Resource.Id.message);
            Button   send      = FindViewById <Button>(Resource.Id.sendButton);

            circular_progress = FindViewById <ProgressBar>(Resource.Id.circularProgressMessageSend);

            if (HomeActivity.fromHome)
            {
                fromEmail = auth.CurrentUser.Email;
                // toEmail will be entered by user
            }
            else
            {
                fromEmail = auth.CurrentUser.Email;
                // 1: Receive toEmail from incoming intent which could either be through profile or through inbox
                // 2: Then insert it into variable
                toEmail        = Intent.GetStringExtra("toEmail") ?? "None";
                recipient.Text = toEmail;
            }

            send.Click += async(sender, e) =>
            {
                if (!recipient.Text.Equals(string.Empty) && !message.Text.Equals(string.Empty))
                {
                    circular_progress.Visibility = ViewStates.Visible;
                    // Check if recipient Email exists or not

                    toEmail = recipient.Text.ToLower().Trim();

                    bool check    = false;
                    var  firebase = new FirebaseClient("https://fir-test-1bdb3.firebaseio.com/");
                    var  items    = await firebase
                                    .Child("users")
                                    .OnceAsync <UserViewModel>();

                    foreach (var item in items)
                    {
                        if (item.Object.Email.Equals(toEmail))
                        {
                            check = true;
                            break;
                        }
                    }

                    if (check)
                    {
                        var item = firebase.Child("messages")
                                   .PostAsync <MessageViewModel>(new MessageViewModel {
                            ToEmail   = toEmail,
                            FromEmail = fromEmail,
                            Body      = message.Text.Trim(),
                            Timestamp = DateTime.Now.ToString()
                        });


                        message.Text = string.Empty;

                        Toast.MakeText(ApplicationContext, "Message Sent", ToastLength.Long).Show();
                    }
                    else
                    {
                        Toast.MakeText(ApplicationContext, "Enter a valid recipient", ToastLength.Long).Show();
                    }
                    circular_progress.Visibility = ViewStates.Invisible;
                }
                else
                {
                    Toast.MakeText(ApplicationContext, "Fill both fields first", ToastLength.Long).Show();
                }
            };
        }
 private async void InsertIntoDB(GameTagViewModel obj)
 {
     var firebase = new FirebaseClient("https://fir-test-1bdb3.firebaseio.com/gamerTags/");
     //firebase.Child("users");
     var item = await firebase.Child("").PostAsync <GameTagViewModel>(obj);
 }
        protected override async void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.ViewOfflineTournaments);

            // Adding views
            circular_progress = FindViewById <ProgressBar>(Resource.Id.circularProgressOfflineTournaments);
            Button    gameTitle          = FindViewById <Button>(Resource.Id.gameTitleOffline);
            ImageView profilePicture     = FindViewById <ImageView>(Resource.Id.profilePictureOfflineTournament);
            Button    adminName          = FindViewById <Button>(Resource.Id.AdminNameOfflineTournament);
            Button    tourneyTitle       = FindViewById <Button>(Resource.Id.TitleOfflineTournament);
            Button    registrationStatus = FindViewById <Button>(Resource.Id.LiveStatusOfflineTournament);
            Button    finishedStatus     = FindViewById <Button>(Resource.Id.FinishedStatusOfflineTournament);
            Button    description        = FindViewById <Button>(Resource.Id.DescriptionOfflineTournament);
            Button    previous           = FindViewById <Button>(Resource.Id.previousTourneyOffline);
            Button    next            = FindViewById <Button>(Resource.Id.nextTourneyOffline);
            Button    eventPageButton = FindViewById <Button>(Resource.Id.ViewEventPageButtonOfflineTournament);

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

            List <TournamentViewModel> query = new List <TournamentViewModel>();


            // Filtering
            foreach (var item in items)
            {
                if (item.Object.online.Equals("false"))
                {
                    query.Add(item.Object);
                }
            }

            query.Reverse();

            // Loading users' data to get profile pictures
            var users = await firebase.Child("users").OnceAsync <UserViewModel>();

            // Loading first item
            int tourneyCounter = 0; // To keep track of opened tournament

            gameTitle.Text = query[0].Game;

            foreach (var item in users)
            {
                if (item.Object.Email.Equals(query[tourneyCounter].AdminID))
                {
                    if (!item.Object.PhotoURL.Equals(string.Empty))
                    {
                        Glide.With(this).Load(item.Object.PhotoURL).Apply(RequestOptions.CircleCropTransform()).Into(profilePicture);
                    }
                    adminName.Text = item.Object.FirstName + " " + item.Object.LastName ?? "";
                }
            }

            tourneyTitle.Text = query[0].Title;

            if (query[0].Live.Equals("false"))
            {
                registrationStatus.Text = "Registrations Open!";
            }
            else
            {
                registrationStatus.Text = "Registrations Closed!";
            }

            if (query[0].Finished.Equals("true"))
            {
                finishedStatus.Text = "Tournament is Over..";
            }
            else
            {
                finishedStatus.Text = "Tournament is still going on!";
            }

            description.Text = "Description:\n\n" + query[0].Description;

            eventPageButton.Enabled      = true;
            circular_progress.Visibility = ViewStates.Invisible;

            next.Click += (sender, e) =>
            {
                if (query.Count() - 1 == tourneyCounter)
                {
                    // No new Tournaments
                    Toast.MakeText(ApplicationContext, "No more tournaments", ToastLength.Short).Show();
                }
                else
                {
                    tourneyCounter++;

                    gameTitle.Text = query[tourneyCounter].Game;

                    foreach (var item in users)
                    {
                        if (item.Object.Email.Equals(query[tourneyCounter].AdminID))
                        {
                            if (!item.Object.PhotoURL.Equals(string.Empty))
                            {
                                Glide.With(this).Load(item.Object.PhotoURL).Apply(RequestOptions.CircleCropTransform()).Into(profilePicture);
                            }
                            adminName.Text = item.Object.FirstName + " " + item.Object.LastName ?? "";
                        }
                    }

                    tourneyTitle.Text = query[tourneyCounter].Title;

                    if (query[tourneyCounter].Live.Equals("false"))
                    {
                        registrationStatus.Text = "Registrations Open!";
                    }
                    else
                    {
                        registrationStatus.Text = "Registrations Closed!";
                    }

                    if (query[tourneyCounter].Finished.Equals("true"))
                    {
                        finishedStatus.Text = "Tournament is Over..";
                    }
                    else
                    {
                        finishedStatus.Text = "Tournament is still going on!";
                    }

                    description.Text = "Description:\n\n" + query[tourneyCounter].Description;
                }
            };

            previous.Click += (sender, e) =>
            {
                if (0 == tourneyCounter)
                {
                    // No new Tournaments
                    Toast.MakeText(ApplicationContext, "No more tournaments", ToastLength.Short).Show();
                }
                else
                {
                    tourneyCounter--;

                    gameTitle.Text = query[0].Game;

                    foreach (var item in users)
                    {
                        if (item.Object.Email.Equals(query[tourneyCounter].AdminID))
                        {
                            if (!item.Object.PhotoURL.Equals(string.Empty))
                            {
                                Glide.With(this).Load(item.Object.PhotoURL).Apply(RequestOptions.CircleCropTransform()).Into(profilePicture);
                            }
                            adminName.Text = item.Object.FirstName + " " + item.Object.LastName ?? "";
                        }
                    }

                    tourneyTitle.Text = query[tourneyCounter].Title;

                    if (query[tourneyCounter].Live.Equals("false"))
                    {
                        registrationStatus.Text = "Registrations Open!";
                    }
                    else
                    {
                        registrationStatus.Text = "Registrations Closed!";
                    }

                    if (query[tourneyCounter].Finished.Equals("true"))
                    {
                        finishedStatus.Text = "Tournament is Over..";
                    }
                    else
                    {
                        finishedStatus.Text = "Tournament is still going on!";
                    }

                    description.Text = "Description:\n\n" + query[tourneyCounter].Description;
                }
            };

            eventPageButton.Click += (sender, e) =>
            {
                Intent viewEventPageActivity = new Intent(ApplicationContext, typeof(ViewEventPageActivity));
                viewEventPageActivity.PutExtra("tourneyID", query[tourneyCounter].TournamentID);
                StartActivity(viewEventPageActivity);
            };

            /*
             * string[] events = new string[query.Count()];
             *
             * for (int i = 0; i < query.Count(); i++)
             * {
             *  events[i] = query.ToList().ElementAt(i).Title + "\n  Tournament ID -  " + query.ToList().ElementAt(i).TournamentID;
             * }
             * ListAdapter = new ArrayAdapter<string>(this, Resource.Layout.ViewOfflineTournaments, events);
             *
             * ListView.ItemClick += (sender, e) =>
             * {
             *  string tourneyID = string.Empty;
             *  tourneyID = ((TextView)e.View).Text;
             *  string[] temps = tourneyID.Split(' ');
             *  tourneyID = temps[temps.Length - 1];
             *   Intent viewEventPageActivity = new Intent(ApplicationContext, typeof(ViewEventPageActivity));
             *   viewEventPageActivity.PutExtra("tourneyID", tourneyID);
             *   StartActivity(viewEventPageActivity);
             * };
             */
        }
        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();
                 */
            };
        }
Exemple #10
0
        protected override async void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.ViewInbox);

            Button    timeStamp      = FindViewById <Button>(Resource.Id.timeStamp);
            ImageView profilePicture = FindViewById <ImageView>(Resource.Id.profilePictureInbox);
            Button    nameAndEmail   = FindViewById <Button>(Resource.Id.nameAndEmailInbox);
            Button    messageBody    = FindViewById <Button>(Resource.Id.messageBodyInbox);
            Button    next           = FindViewById <Button>(Resource.Id.nextMessage);
            Button    previous       = FindViewById <Button>(Resource.Id.previousMessage);
            EditText  replyText      = FindViewById <EditText>(Resource.Id.replyBodyInbox);
            Button    reply          = FindViewById <Button>(Resource.Id.replyButton);

            circular_progress = FindViewById <ProgressBar>(Resource.Id.circularProgressInbox);

            nameAndEmail.Enabled = false;
            messageBody.Enabled  = false;
            timeStamp.Enabled    = false;

            auth    = FirebaseAuth.GetInstance(MainActivity.app);
            toEmail = auth.CurrentUser.Email;

            circular_progress.Visibility = ViewStates.Visible;
            // Loading messages
            var firebase = new FirebaseClient("https://fir-test-1bdb3.firebaseio.com/");
            var items    = await firebase
                           .Child("messages")
                           .OnceAsync <MessageViewModel>();

            // Loading users' data to get profile pictures
            var users = await firebase.Child("users").OnceAsync <UserViewModel>();

            List <MessageViewModel> query = new List <MessageViewModel>();

            // Filtering
            foreach (var item in items)
            {
                if (item.Object.ToEmail.Equals(toEmail))
                {
                    query.Add(item.Object);
                }
            }

            query.Reverse();

            int messageNumber = 0; // To keep track of messages

            timeStamp.Text = query[messageNumber].Timestamp;


            foreach (var item in users)
            {
                if (item.Object.Email.Equals(query[messageNumber].FromEmail))
                {
                    if (!item.Object.PhotoURL.Equals(string.Empty))
                    {
                        Glide.With(this).Load(item.Object.PhotoURL).Apply(RequestOptions.CircleCropTransform()).Into(profilePicture);
                    }
                    nameAndEmail.Text = item.Object.FirstName + " " + item.Object.LastName ?? "";
                }
            }

            messageBody.Text = query[messageNumber].FromEmail + " says: \n\n" + query[messageNumber].Body;

            circular_progress.Visibility = ViewStates.Invisible;

            next.Click += (sender, e) =>
            {
                int a = query.Count();
                if (query.Count() - 1 == messageNumber)
                {
                    // No new messages
                    Toast.MakeText(ApplicationContext, "No more messages", ToastLength.Short).Show();
                }
                else
                {
                    circular_progress.Visibility = ViewStates.Visible;

                    messageNumber++;

                    timeStamp.Text = query[messageNumber].Timestamp;


                    foreach (var item in users)
                    {
                        if (item.Object.Email.Equals(query[messageNumber].FromEmail))
                        {
                            if (!item.Object.PhotoURL.Equals(string.Empty))
                            {
                                Glide.With(this).Load(item.Object.PhotoURL).Apply(RequestOptions.CircleCropTransform()).Into(profilePicture);
                            }
                            nameAndEmail.Text = item.Object.FirstName + " " + item.Object.LastName ?? "";
                        }
                    }

                    messageBody.Text = query[messageNumber].FromEmail + " says: \n\n" + query[messageNumber].Body;

                    circular_progress.Visibility = ViewStates.Invisible;
                }
            };

            previous.Click += (sender, e) =>
            {
                int a = query.Count();
                if (messageNumber == 0)
                {
                    // No new messages
                    Toast.MakeText(ApplicationContext, "No more messages", ToastLength.Short).Show();
                }
                else
                {
                    circular_progress.Visibility = ViewStates.Visible;

                    messageNumber--;

                    timeStamp.Text = query[messageNumber].Timestamp;


                    foreach (var item in users)
                    {
                        if (item.Object.Email.Equals(query[messageNumber].FromEmail))
                        {
                            if (!item.Object.PhotoURL.Equals(string.Empty))
                            {
                                Glide.With(this).Load(item.Object.PhotoURL).Apply(RequestOptions.CircleCropTransform()).Into(profilePicture);
                            }
                            nameAndEmail.Text = item.Object.FirstName + " " + item.Object.LastName ?? "";
                        }
                    }

                    messageBody.Text = query[messageNumber].FromEmail + " says: \n\n" + query[messageNumber].Body;

                    circular_progress.Visibility = ViewStates.Invisible;
                }
            };

            reply.Click += (sender, e) =>
            {
                circular_progress.Visibility = ViewStates.Visible;
                if (!replyText.Text.Equals(string.Empty))
                {
                    var item = firebase.Child("messages")
                               .PostAsync <MessageViewModel>(new MessageViewModel
                    {
                        ToEmail   = query[messageNumber].FromEmail,
                        FromEmail = auth.CurrentUser.Email,
                        Body      = replyText.Text.Trim(),
                        Timestamp = DateTime.Now.ToString()
                    });


                    replyText.Text = string.Empty;

                    Toast.MakeText(ApplicationContext, "Message Sent", ToastLength.Short).Show();
                }
                else
                {
                    Toast.MakeText(ApplicationContext, "Enter a reply first", ToastLength.Short).Show();
                }
                circular_progress.Visibility = ViewStates.Invisible;
            };

            /*
             * string[] messages = new string[query.Count()];
             *
             * for (int i = 0; i < query.Count(); i++)
             * {
             *  messages[i] = query.ToList().ElementAt(i).Timestamp + "\n" + query.ToList().ElementAt(i).Body + "\n  -  " + query.ToList().ElementAt(i).FromEmail;
             *
             * }
             * ListAdapter = new ArrayAdapter<string>(this, Resource.Layout.ViewInbox, messages);
             *
             * ListView.ItemClick += (sender, e) =>
             * {
             *  string recipient = string.Empty;
             *  recipient = ((TextView)e.View).Text;
             *  string[] temps = recipient.Split(' ');
             *  recipient = temps[temps.Length - 1];
             *  Intent sendMessageActivity = new Intent(ApplicationContext, typeof(MessageSendActivity));
             *  sendMessageActivity.PutExtra("toEmail", recipient);
             *  HomeActivity.fromHome = false;
             *  StartActivity(sendMessageActivity);
             * };
             */
        }
Exemple #11
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();
                }
            };
        }