using System;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using System.Threading.Tasks;
using Xamarin.Essentials;
using Firebase.Database;
using Firebase.Database.Query;
using System.Collections.Generic;
using Firebase.Auth;
using Newtonsoft.Json;
using System.IO;
using System.Collections.ObjectModel;

namespace EcoFootprintCalculator
{
    public class activechallenge
    {
        public Regularity regularity { get; set; }
        public string task { get; set; }
        public double task_value { get; set; }
        public int passed_days { get; set; }
        public int counter { get; set; }

        public activechallenge(Regularity regularity, string task, double task_value, int passed_days, int counter)
        {
            this.regularity = regularity;
            this.task = task;
            this.task_value = task_value;
            this.passed_days = passed_days;
            this.counter = counter;
        }

        public activechallenge()
        {

        }
    }

    
    public enum Regularity
    {
        Never = 0,
        Yearly = 1,
        Semiyearly = 2,
        Seasonally = 4,
        Bimonthly = 6,
        Monthly = 12,
        Biweekly = 26,
        Weekly = 52,
        Semiweekly = 104,
        Bidiurnally = 188,
        Daily = 365
    };
    public class weeklytips
    {
        public string tip { get; set; }
        public double point { get; set; }
        public Regularity[] regularities { get; set; } 

        public weeklytips(string tip, double point, Regularity[] regularities)
        {
            this.tip = tip;
            this.point = point;
            this.regularities = regularities;
        }
    }
    public class CountryFootprint
    {
        public string Country { get; set; }
        public double CountryEcoFootprint { get; set; }
        public double CountryReductfromtip { get; set; }
        public double NumberofUsersofCountry { get; set; }
    }

    public class AllFootprint
    {
        public double AllEcoFootprint { get; set; }
        public double AllReductfromtips { get; set; }
        public double NumberofallUser { get; set; }
    }
    public class Users
    {
        public double Water1 { get; set; }
        public double Water2 { get; set; }
        public double Water3 { get; set; }
        public double Water4 { get; set; }
        public double Water5 { get; set; }
        public double Water6 { get; set; }
        public double Water7 { get; set; }
        public double Food1 { get; set; }
        public double Food2 { get; set; }
        public double Food3 { get; set; }
        public double Food4 { get; set; }
        public double Food5 { get; set; }
        public double Food6 { get; set; }
        public double Food7 { get; set; }
        public double Transport1 { get; set; }
        public double Transport2 { get; set; }
        public double Transport3 { get; set; }
        public double Transport4 { get; set; }
        public double Transport5 { get; set; }
        public double Transport6 { get; set; }
        public double Shelter1 { get; set; }
        public double Shelter2 { get; set; }
        public double Shelter3 { get; set; }
        public double Energy1 { get; set; }
        public double Energy2 { get; set; }
        public double Energy3 { get; set; }
        public double Energy4 { get; set; }
        public double Energy5 { get; set; }
        public double Energy6 { get; set; }
        public double Energy7 { get; set; }
        public double Cloth1 { get; set; }
        public double Cloth2 { get; set; }
        public double Cloth3 { get; set; }
        public double Cloth4 { get; set; }
        public double Cloth5 { get; set; }
        public double Cloth6 { get; set; }
        public double Cloth7 { get; set; }
        public double Cloth8 { get; set; }
        public double Waste1 { get; set; }
        public double Waste2 { get; set; }
        public double Waste3 { get; set; }
        public double Waste4 { get; set; }
        public double Waste5 { get; set; }
        public double Waste6 { get; set; }
        public double Waste7 { get; set; }
        public double Fun1 { get; set; }
        public double Fun2 { get; set; }
        public double Fun3 { get; set; }

        public string Country { get; set; }
        public double Reductionfromtips { get; set; }
        

        public double Ecofootprint { get; set; }
    }
    public partial class App : Application
    {
        public static double allwater, water1, water2, water3, water4, water5, water6, water7;
        public static double water1value, water2value, water3value, water4value, water5value, water6value, water7value;
        public static double allfood, food1, food2, food3, food4, food5, food6, food7;
        public static double food1value_1, food1value_2, food1value_3, food1value_4, food1value_5, food1value_6, food1value_7, food1value_8, food1value_9, food2value, food3value, food4value, food5value, food6value, food7value;
        public static double alltransport, transport1, transport2, transport3, transport4, transport5, transport6;
        public static double transport1value_1, transport1value_2, transport1value_3, transport1value_4, transport2value, transport3value, transport4value, transport5value, transport6value;
        public static double allshelter, shelter1, shelter2, shelter3;
        public static double shelter1value, shelter2value, shelter3value;
        public static double allenergy, energy1, energy2, energy3, energy4, energy5, energy6, energy7;
        public static double energy1value, energy2value, energy3value, energy4value, energy5value, energy6value, energy7value;
        public static double allcloth, cloth1, cloth2, cloth3, cloth4, cloth5, cloth6, cloth7, cloth8;
        public static double cloth1value, cloth2value, cloth3value, cloth4value, cloth5value, cloth6value, cloth7value, cloth8value;
        public static double allwaste, waste1, waste2, waste3, waste4, waste5, waste6, waste7;
        public static double waste1value, waste2value, waste3value, waste4value, waste5value, waste6value, waste7value;
        public static double allfun, fun1, fun2, fun3;
        public static double fun1value, fun2value, fun3value;
        public static double reductionfromtips;
        public static double calculatedecofootprint;
        public static double weekoftheyear;
        public static bool answered;
        public static bool weekoftheyearchanged;
        public static double dayoftheyear;
        public static bool dayoftheyearchanged;
        public static int daylyfactrow;
        public static string country;

        // !!!!!!!!!!!!!!!!!!!!!!!!!!!! add your databe access data here !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        public const string ApiKey = "YOUR FIREBASE API KEY";
        public const string ServerAddress = "YOUR FIREBASE DATABASE ADDRESS";
        public static FirebaseAuthProvider authProvider;
        public static FirebaseAuth auth;
        public static FirebaseClient firebaseClient;
        public static string refreshtoken;
        public static CountryFootprint countryFootprint = new CountryFootprint();
        public static AllFootprint allFootprint = new AllFootprint();
        public static Users user = new Users();
        public static string uploaderror;
        public static string downloadcountryerror;
        public static string downloadallerror;
        public static string loginerror;

        public static bool updatealreadydone;
        public static List<weeklytips> weeklytipslist;
        public static List<string> dailyfacts;
        public static List<weeklytips> chosentips;
        public static LinearGradientBrush bgcolor;

        public static int dayspassedsincelastlogin;

        public static activechallenge activechallenge = new activechallenge();
        public static List<activechallenge> activechallenges = new List<activechallenge>();
        public static ObservableCollection<activechallenge> activechallengesO = new ObservableCollection<activechallenge>();
        public static List<activechallenge> tempchallenges = new List<activechallenge>();
        public static string activechallangejson = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "ach.json");

        public static double screenheight;

        public App()
        {
            InitializeComponent();

            weekoftheyearchanged = false;
            dayoftheyearchanged = false;

            weekoftheyearchecker();
            daychangedchecker();

            updatealreadydone = false;

            GradientStopCollection gradcoll = new GradientStopCollection();
            gradcoll.Add(new GradientStop(color: Color.FromHex("ECF78B"), offset: (float)0.2));
            gradcoll.Add(new GradientStop(color: Color.FromHex("3EB489"), offset: (float)0.8));

            bgcolor = new LinearGradientBrush(gradcoll, startPoint: Point.Zero, endPoint: new Point(1, 1));

            try
            {
                loginerror = "";
                var task = Task.Run(() => loginanomifnotyet());
                if (task.Wait(TimeSpan.FromSeconds(5)))
                {
                    auth = task.Result;
                    recalculateecofootprint();
                }
                else
                    throw new Exception("Timed out");
            }
            catch (Exception ex)
            {
                loginerror = "There are connection issues!\n Your internet might be slowed down!";
                auth.ExpiresIn = 0;
                auth.FirebaseToken = "";
                auth.RefreshToken = "";
                auth.User = new User();
                auth.User.LocalId = "";
                auth.Created = DateTime.Now;
            }

            weeklytipslist = new List<weeklytips>
            {
                new weeklytips("Introduce this application to a friend", 2, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally,Regularity.Bimonthly, Regularity.Monthly, Regularity.Biweekly, Regularity.Weekly, Regularity.Semiweekly, Regularity.Bidiurnally, Regularity.Daily }),
                new weeklytips("Organize an event in a theme of environment protection", 10, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally,Regularity.Bimonthly, Regularity.Monthly, Regularity.Biweekly }),
                new weeklytips("Organize a trash collecting event to clear a big polluted area", 30, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally,Regularity.Bimonthly, Regularity.Monthly }),
                new weeklytips("Collect 100L of trash from your surrounding area", 8, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally,Regularity.Bimonthly, Regularity.Monthly, Regularity.Biweekly, Regularity.Weekly }),
                new weeklytips("Turn the heating to 18° for the evening", 2, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally,Regularity.Bimonthly, Regularity.Monthly, Regularity.Biweekly, Regularity.Weekly, Regularity.Semiweekly, Regularity.Bidiurnally, Regularity.Daily }),
                new weeklytips("Use your outfit from yesterday", 0.3, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally,Regularity.Bimonthly, Regularity.Monthly, Regularity.Biweekly, Regularity.Weekly, Regularity.Semiweekly, Regularity.Bidiurnally}),
                new weeklytips("Fix one of your torn cloth and wear it", 4, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally,Regularity.Bimonthly, Regularity.Monthly}),
                new weeklytips("Next time buy a secondhand cloth instead of a new", 15, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally}),
                new weeklytips("Give your no longer used clothes to a local thrift store", 20, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally}),
                new weeklytips("Next time buy a hemp shirt insted of cotton", 15, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally}),
                new weeklytips("Wear a cloth that you have never weared from your collection", 0.8, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally,Regularity.Bimonthly, Regularity.Monthly, Regularity.Biweekly, Regularity.Weekly, Regularity.Semiweekly}),
                new weeklytips("Reduce the number of shoes you have, by giving one to a local thrift store", 20, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally }),
                new weeklytips("Dry the washed clothes outdoors", 1, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally,Regularity.Bimonthly, Regularity.Monthly, Regularity.Biweekly, Regularity.Weekly, Regularity.Semiweekly }),
                new weeklytips("Change a light bulb to a compact fluorescent one", 40, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly }),
                new weeklytips("Turn off everything you don't use", 0.2, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally,Regularity.Bimonthly, Regularity.Monthly, Regularity.Biweekly, Regularity.Weekly, Regularity.Semiweekly, Regularity.Bidiurnally, Regularity.Daily } ),
                new weeklytips("Do not use airconditioning for a day", 0.2, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally,Regularity.Bimonthly, Regularity.Monthly, Regularity.Biweekly, Regularity.Weekly, Regularity.Semiweekly, Regularity.Bidiurnally, Regularity.Daily } ),
                new weeklytips("Spend 3 hours outdoors today", 0.5, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally,Regularity.Bimonthly, Regularity.Monthly, Regularity.Biweekly, Regularity.Weekly, Regularity.Semiweekly, Regularity.Bidiurnally, Regularity.Daily } ),
                new weeklytips("Eat something vegetarian today", 0.1, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally,Regularity.Bimonthly, Regularity.Monthly, Regularity.Biweekly, Regularity.Weekly, Regularity.Semiweekly, Regularity.Bidiurnally, Regularity.Daily } ),
                new weeklytips("Purchase from a local market", 0.05, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally,Regularity.Bimonthly, Regularity.Monthly, Regularity.Biweekly, Regularity.Weekly, Regularity.Semiweekly } ),
                new weeklytips("Purchase organic food", 0.05, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally,Regularity.Bimonthly, Regularity.Monthly, Regularity.Biweekly, Regularity.Weekly, Regularity.Semiweekly, Regularity.Bidiurnally } ),
                new weeklytips("Buy seasonal food", 0.05, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally,Regularity.Bimonthly, Regularity.Monthly, Regularity.Biweekly, Regularity.Weekly, Regularity.Semiweekly, Regularity.Bidiurnally, Regularity.Daily } ),
                new weeklytips("Compost the fruit/vegetabels scraps amd peels", 0.1, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally,Regularity.Bimonthly, Regularity.Monthly, Regularity.Biweekly, Regularity.Weekly, Regularity.Semiweekly } ),
                new weeklytips("Freeze leftover food", 0.01, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally,Regularity.Bimonthly, Regularity.Monthly, Regularity.Biweekly, Regularity.Weekly, Regularity.Semiweekly, Regularity.Bidiurnally, Regularity.Daily } ),
                new weeklytips("Don't buy processed food", 0.1, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally,Regularity.Bimonthly, Regularity.Monthly, Regularity.Biweekly, Regularity.Weekly, Regularity.Semiweekly } ),
                new weeklytips("Don't buy packaged food", 0.1, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally,Regularity.Bimonthly, Regularity.Monthly, Regularity.Biweekly, Regularity.Weekly, Regularity.Semiweekly } ),
                new weeklytips("Don't let any of your food to become waste", 0.5, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally,Regularity.Bimonthly, Regularity.Monthly, Regularity.Biweekly, Regularity.Weekly, Regularity.Semiweekly, Regularity.Bidiurnally, Regularity.Daily } ),
                new weeklytips("Use less space than you usually need for your leisure activities", 0.1, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally,Regularity.Bimonthly, Regularity.Monthly, Regularity.Biweekly, Regularity.Weekly, Regularity.Semiweekly, Regularity.Bidiurnally, Regularity.Daily } ),
                new weeklytips("Go outside and read a book insted of watching tv or using the computer", 0.2, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally,Regularity.Bimonthly, Regularity.Monthly, Regularity.Biweekly, Regularity.Weekly, Regularity.Semiweekly, Regularity.Bidiurnally, Regularity.Daily } ),
                new weeklytips("Reduce the usually needed number of equipments for your leisure activities", 0.1, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally,Regularity.Bimonthly, Regularity.Monthly, Regularity.Biweekly, Regularity.Weekly, Regularity.Semiweekly, Regularity.Bidiurnally, Regularity.Daily } ),
                new weeklytips("Invite a family member in need to live at your house for a week", 0.05, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally,Regularity.Bimonthly, Regularity.Monthly, Regularity.Biweekly, Regularity.Weekly } ),
                new weeklytips("Travel on foot", 0.3, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally,Regularity.Bimonthly, Regularity.Monthly, Regularity.Biweekly, Regularity.Weekly, Regularity.Semiweekly, Regularity.Bidiurnally, Regularity.Daily } ),
                new weeklytips("Don't use any vehicle today", 0.3, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally,Regularity.Bimonthly, Regularity.Monthly, Regularity.Biweekly, Regularity.Weekly, Regularity.Semiweekly, Regularity.Bidiurnally, Regularity.Daily } ),
                new weeklytips("Go out and have a walk", 0.05, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally,Regularity.Bimonthly, Regularity.Monthly, Regularity.Biweekly, Regularity.Weekly, Regularity.Semiweekly, Regularity.Bidiurnally, Regularity.Daily } ),
                new weeklytips("Don't create garbage today", 0.01, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally,Regularity.Bimonthly, Regularity.Monthly, Regularity.Biweekly, Regularity.Weekly, Regularity.Semiweekly, Regularity.Bidiurnally, Regularity.Daily } ),
                new weeklytips("Reuse an item instead of throwing it out", 2, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally,Regularity.Bimonthly, Regularity.Monthly } ),
                new weeklytips("Repair a broken item", 2, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally,Regularity.Bimonthly, Regularity.Monthly } ),
                new weeklytips("Don't buy any disposable item", 0.3, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally,Regularity.Bimonthly, Regularity.Monthly, Regularity.Biweekly, Regularity.Weekly, Regularity.Semiweekly } ),
                new weeklytips("Switch some batteries to rechargable", 1, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally,Regularity.Bimonthly, Regularity.Monthly } ),
                new weeklytips("Spend less today", 0.5, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally,Regularity.Bimonthly, Regularity.Monthly, Regularity.Biweekly, Regularity.Weekly, Regularity.Semiweekly, Regularity.Bidiurnally, Regularity.Daily } ),
                new weeklytips("Don't shower/bath today", 0.5, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally,Regularity.Bimonthly, Regularity.Monthly, Regularity.Biweekly, Regularity.Weekly, Regularity.Semiweekly, Regularity.Bidiurnally } ),
                new weeklytips("Put in the toilet water basin an object that reduces the capacity of water in it", 20, new Regularity[]{ Regularity.Never, Regularity.Yearly } ),
                new weeklytips("Instead of letting the water flow, fill in a cup of water and rinse your toothbrush in it", 0.1, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally,Regularity.Bimonthly, Regularity.Monthly, Regularity.Biweekly, Regularity.Weekly, Regularity.Semiweekly, Regularity.Bidiurnally, Regularity.Daily } ),
                new weeklytips("Use the leftovers to cook other foods", 1, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally,Regularity.Bimonthly, Regularity.Monthly, Regularity.Biweekly, Regularity.Weekly, Regularity.Semiweekly } ),
                new weeklytips("Grow your own herbs", 20, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally } ),
                new weeklytips("Transform one of your old cloth. (e.g.: making short pants from long pants, a T-shirt from a sweater)", 10, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally,Regularity.Bimonthly } ),
                new weeklytips("Buy a cloth that have already been recycled", 10, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally,Regularity.Bimonthly } ),
                new weeklytips("Make a decorative element from pieces of clothing like a necklace", 5, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally,Regularity.Bimonthly } ),
                new weeklytips("Use canvas bag instead of disposable bags", 0.5, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally,Regularity.Bimonthly, Regularity.Monthly, Regularity.Biweekly, Regularity.Weekly, Regularity.Semiweekly } ),
                new weeklytips("Eat something with a warranty period that has expired within a certain time frame", 0.5, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally,Regularity.Bimonthly, Regularity.Monthly, Regularity.Biweekly, Regularity.Weekly } ),
                new weeklytips("Preserve the vegetables and fruits you grow. eg: jam, pickles, tomato puree", 30, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally } ),
                new weeklytips("Ask your parents to take your friends too to the school if you must go by car", 1, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally,Regularity.Bimonthly, Regularity.Monthly, Regularity.Biweekly, Regularity.Weekly, Regularity.Semiweekly, Regularity.Bidiurnally, Regularity.Daily } ),
                new weeklytips("Use natural materials as cleaning agents, e.g. citric acid, baking soda, vinegar", 0.1, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally,Regularity.Bimonthly, Regularity.Monthly, Regularity.Biweekly, Regularity.Weekly, Regularity.Semiweekly, Regularity.Bidiurnally, Regularity.Daily } ),
                new weeklytips("Buy a plant to keep in the apartment", 15, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally } ),
                new weeklytips("Don't use aerosol products today, e.g. Spray. air freshener", 0.2, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally,Regularity.Bimonthly, Regularity.Monthly, Regularity.Biweekly, Regularity.Weekly, Regularity.Semiweekly, Regularity.Bidiurnally, Regularity.Daily } ),
                new weeklytips("Collect the coffee grounds to use it later (plants, cleaning, pesticide)", 0.03, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally,Regularity.Bimonthly, Regularity.Monthly, Regularity.Biweekly, Regularity.Weekly, Regularity.Semiweekly, Regularity.Bidiurnally, Regularity.Daily } ),
                new weeklytips("Create a bird feeder out of a plastic bottle", 5, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally,Regularity.Bimonthly, Regularity.Monthly } ),
                new weeklytips("Plant a tree at home and or in public space or park.", 2, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally,Regularity.Bimonthly, Regularity.Monthly, Regularity.Biweekly, Regularity.Weekly, Regularity.Semiweekly, Regularity.Bidiurnally, Regularity.Daily } ),
                new weeklytips("Filter the cooking oil so that it can be used again", 1.5, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally,Regularity.Bimonthly, Regularity.Monthly, Regularity.Biweekly, Regularity.Weekly } ),
                new weeklytips("Hand in the cooking oil that can no longer be used at a collection point", 10, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally,Regularity.Bimonthly } ),
                new weeklytips("Collect the rainwater to water the plants", 1, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally,Regularity.Bimonthly, Regularity.Monthly, Regularity.Biweekly, Regularity.Weekly } ),
                new weeklytips("Use a water filter jug, instead of bottled water", 0.01, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally,Regularity.Bimonthly, Regularity.Monthly, Regularity.Biweekly, Regularity.Weekly, Regularity.Semiweekly, Regularity.Bidiurnally, Regularity.Daily } ),
                new weeklytips("While showering, close the faucet while soaping yourself", 0.5, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally,Regularity.Bimonthly, Regularity.Monthly, Regularity.Biweekly, Regularity.Weekly, Regularity.Semiweekly, Regularity.Bidiurnally, Regularity.Daily } ),
                new weeklytips("Wash the ingredients used for cooking in a bowl instead of under a running-water", 1, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally,Regularity.Bimonthly, Regularity.Monthly, Regularity.Biweekly, Regularity.Weekly, Regularity.Semiweekly } ),
                new weeklytips("Only fill the kettle with as much water as is necessary", 0.1, new Regularity[]{ Regularity.Never, Regularity.Yearly, Regularity.Semiyearly, Regularity.Seasonally,Regularity.Bimonthly, Regularity.Monthly, Regularity.Biweekly, Regularity.Weekly, Regularity.Semiweekly, Regularity.Bidiurnally } )
            };

            dailyfacts = new List<string>
            {
                "During the production of 1 kg of beef, approx. 27 kg of carbon dioxide enters the air (in the meantime, a lot of methane is also produced, which is a greenhouse gas 23 times more intense than carbon dioxide)",
                "Production of 1 kg of beef is associated with approx. 100 km of driving carbon dioxide emissions",
                "Ammonia is a byproduct of large-scale poultry farming, which significantly contributes to the formation of acid rain",
                "Cattle keeping requires approx. 10 times as much grain use to create the same number of calories as a vegetarian diet (this amount used could feed several countries throughout the year)",
                "If we go meat-free for just one day a week for 10 years, we burden the environment with 1 ton less carbon dioxide",
                "70% of the Earth's fresh water resources are used for food production (plant cultivation, livestock breeding)",
                "The environmental impact of a diet based on the meat of farm animals is 2-5 times greater than that of a low-meat diet, e.g. On average, 100 times more water is used (and polluted) to produce 1 kg of meat than to grow 1 kg of crops",
                "To produce 1 kg of beef approx. 15,000 liters! of water is used, so 1 nice slice of steak is about 107! bathtubs of water",
                "Gases containing sulfur and nitrogen in the air can travel up to 1,500-3,000 km by the wind, causing acid rain in the given area",
                "Poisoning caused by environmental pollution kills 1.5 times more than smoking, three times more than AIDS, tuberculosis and malaria combined, six times more than road accidents and 15 times more than wars or violence in the form of Most deaths – 6.5 million – are attributable to air pollution",
                "The world's oceans are currently polluted by 150 million tons of plastic, and according to estimates, 4.8-12.7 million tons enter the ocean every year, the vast majority of which is single-use plastic",
                "The most number of trees planted in one hour is 26422",
                "Two-thirds of our planet is water, of which less than 1% is drinkable",
                "Americans use 2.5 million plastic bottles every two hours",
                "Recycling an aluminum box saves enough energy to run the TV for 3 hours",
                "Every day, 25,000 trees are cut down to produce toilet paper",
                "Since 1972, we have celebrated World Environment Protection Day on 5th of June",
                "Our Earth is also called the blue planet because 71% of it is water, of which only 1% is drinking water",
                "There is so much salt in our seas and oceans that it could cover the entire landmass of the Earth, approximately 152 meters high",
                "During the production of a microchip, a bucket of hazardous waste is generated",
                "Last summer, 90 tons of garbage were collected on the beaches of Bali during one weekend",
                "Due to environmental pollution, the number of areas covered by coral reefs in the world has halved since the 1950s",
                "Every fifth bird species in the world and 13% of the bird population in Europe are threatened with extinction due to the effects of environmental pollution and global warming",
                "While in the 1950s we produced approximately 1.5 million tons of plastic annually globally, in 2018 this number had already reached 359 million",
                "Only in the first decade of the 21st century we produced as much plastic worldwide as in the last century altogether",
                "According to the latest estimates, roughly 10 tons of plastic are produced every second",
                "As a consequence of the rapid growth of production and consumption, since the 1950s, we have burdened our planet with 8.3 billion tons of plastic",
                "If we do not change the current production and consumption habits, by 2050 plastic production will account for 20% of the world's total petroleum consumption instead of the current 4-6%",
                "There is a large company that globally produces 120 billion PET bottles in a single year, that is, 3,800 pieces come off the assembly line every second",
                "Many people like to refill PET bottles, thereby extending the useful phase of the product's life cycle. However, we now know that this is a very bad idea, as bacteria and mold appear in the bottles already 24 hours after opening",
                "In a single week, up to 900,000 bacterial colonies can settle in opened PET bottles, per square centimeter",
                "If we take the total weight as a benchmark, it can be said that the ratio of fish to plastic waste in the world's seas and oceans is currently 5:1",
                "The seas and oceans are polluted by approximately 150 million tons of plastic waste, which threatens 700 species of aquatic animals",
                "Researchers have found plastic waste in the bodies of 90% of seabirds and 50% of turtles",
                "Based on the data measured in recent years, approximately 850 million tons of greenhouse gases entered the atmosphere globally due to the production of plastic products and the incineration of waste generated from them. If we do not reduce plastic production, by 2050 we will release 2.8 billion tons of harmful gases into the air every year",
                "500 million plastic straws are used every day in America alone. Arranged in a row, this amount would circle the Earth twice",
                "Every minute, nearly 2 million tons of single-use plastic bags are sold worldwide",
                "100 billion plastic bags are used annually in America alone. Tied together, this many bags would circle the Earth along the equator 773 times!",
                "8 million tons of plastic end up in the oceans every year. If you put all of this in plastic garbage bags, you would end up with 5 full bags per square centimeter of the beaches every year",
                "There are more microplastics in the oceans than stars in the Milky Way",
                "If the pace of plastic production does not slow down, by 2050 the weight of plastic waste will outweigh the weight of fish",
                "More than 250 billion aluminum cans are produced in the world every year",
                "The aluminum boxes can be easily and simply recycled, It takes approx. 60 days to recycle it",
                "There are lakes that \"explode\" and release poisonous gases into the air. In Lake Kivu, for example, the wildlife dies out every thousand years because of this. The gas chemical composition of the explosive lakes is different, but it can be said about them that one of their eruptions would be fatal: millions of people would die because of the released gases",
                "There is also light pollution, which is unnecessary and energy-wasting lighting with artificial light sources, which disturbs the natural biorhythm of the animals and humans and increases environmental pollution",
                "The average daily water consumption of a person reaches 50 liters",
                "140 liters of water are used to produce the coffee beans needed for one cup of coffee, while 5,000 liters of water are needed for 1 kg of rice (some of this is recycled)",
                "A piece of discarded cigarette strip on solid ground pollutes approx. 1 cubic meter of groundwater",
                "Medicines with an expired warranty period are considered hazardous waste, which must not be thrown in the trash or toilet, but can be returned at any pharmacy",
                "Some cars also run on used cooking oil",
                "Office furniture and armchairs, whose load capacity exceeded 100 kg, have already been made from recycled corrugated cardboard",
                "Decomposition time of paper towel: 2-4 weeks",
                "Decomposition time of paper box: 4-8 weeks",
                "Decomposition time of banana peel: 3-4 weeks",
                "Decomposition time of leaflets: 6 weeks",
                "Decomposition time of cigarette butt: 10-12 years",
                "Decomposition time of leather shoes: 25-40 years",
                "Decomposition time of aluminum can: 200-500 years",
                "Decomposition time of plastic bottle: 450 years",
                "Decomposition time of disposable diaper: 550 years",
                "Decomposition time of plastic bags: 200-1000 years",
                "Decomposition time of plastic box: 1 million years",
                "Decomposition time of glass: 1-2 million years",
                "Decomposition time of styrofoam: minimum 1 million years"
            };

            tipspicker();
            daylyfactpicker();

            dayspassedsincelastlogin_calc();

            //File.Delete(activechallangejson);

            readjason();

            uploaderror = "";
            downloadcountryerror = "";
            downloadallerror = "";
        }

        protected override void OnStart()
        {            
            MainPage = new Navigation();            
        }

        protected override void OnSleep()
        {
        }

        protected override void OnResume()
        {
        }

        public static FirebaseAuth loginanomifnotyet()
        {
            authProvider = new FirebaseAuthProvider(new FirebaseConfig(ApiKey));
            refreshtoken = Convert.ToString(Preferences.Get("refreshtoken", "0"));
            if (refreshtoken == "0")
            {
                try
                {
                    auth = authProvider.SignInAnonymouslyAsync().Result;
                    firebaseClient = new FirebaseClient(
                      ServerAddress,
                      new FirebaseOptions
                      {
                          AuthTokenAsyncFactory = () => Task.FromResult(auth.FirebaseToken)
                      });
                    Preferences.Set("refreshtoken", auth.RefreshToken);
                    return auth;
                }
                catch(Exception ex)
                {
                    loginerror = ex.ToString();
                    auth.ExpiresIn = 0;
                    auth.FirebaseToken = "";
                    auth.RefreshToken = "";
                    auth.User = new User();
                    auth.User.LocalId = "";
                    auth.Created = DateTime.Now;
                    return auth;
                }
            }
            else
            {
                try
                {
                    auth = new FirebaseAuth();
                    auth.RefreshToken = refreshtoken;                    
                    auth = authProvider.RefreshAuthAsync(auth).Result;
                    auth.User = authProvider.GetUserAsync(auth.FirebaseToken).Result;
                    firebaseClient = new FirebaseClient(
                      ServerAddress,
                      new FirebaseOptions
                      {
                          AuthTokenAsyncFactory = () => Task.FromResult(auth.FirebaseToken)
                      });
                    return auth;
                }
                catch
                {
                    try
                    {
                        auth = authProvider.SignInAnonymouslyAsync().Result;
                        firebaseClient = new FirebaseClient(
                         ServerAddress,
                         new FirebaseOptions
                         {
                             AuthTokenAsyncFactory = () => Task.FromResult(auth.FirebaseToken)
                         });
                        Preferences.Set("refreshtoken", auth.RefreshToken);
                        return auth;
                    }
                    catch(Exception ex)
                    {
                        loginerror = ex.ToString();
                        auth.ExpiresIn = 0;
                        auth.FirebaseToken = "";
                        auth.RefreshToken = "";
                        auth.User = new User();
                        auth.User.LocalId = "";
                        auth.Created = DateTime.Now;
                        return auth;
                    }
                }
            }
        }

        public static async Task uploaduserdata()
        {
            user.Water1 = water1;
            user.Water2 = water2;
            user.Water3 = water3;
            user.Water4 = water4;
            user.Water5 = water5;
            user.Water6 = water6;
            user.Water7 = water7;
            user.Food1 = food1;
            user.Food2 = food2;
            user.Food3 = food3;
            user.Food4 = food4;
            user.Food5 = food5;
            user.Food6 = food6;
            user.Food7 = food7;
            user.Transport1 = transport1;
            user.Transport2 = transport2;
            user.Transport3 = transport3;
            user.Transport4 = transport4;
            user.Transport5 = transport5;
            user.Transport6 = transport6;
            user.Shelter1 = shelter1;
            user.Shelter2 = shelter2;
            user.Shelter3 = shelter3;
            user.Energy1 = energy1;
            user.Energy2 = energy2;
            user.Energy3 = energy3;
            user.Energy4 = energy4;
            user.Energy5 = energy5;
            user.Energy6 = energy6;
            user.Energy7 = energy7;
            user.Cloth1 = cloth1;
            user.Cloth2 = cloth2;
            user.Cloth3 = cloth3;
            user.Cloth4 = cloth4;
            user.Cloth5 = cloth5;
            user.Cloth6 = cloth6;
            user.Cloth7 = cloth7;
            user.Cloth8 = cloth8;
            user.Waste1 = waste1;
            user.Waste2 = waste2;
            user.Waste3 = waste3;
            user.Waste4 = waste4;
            user.Waste5 = waste5;
            user.Waste6 = waste6;
            user.Waste7 = waste7;
            user.Fun1 = fun1;
            user.Fun2 = fun2;
            user.Fun3 = fun3;
            user.Country = country;
            user.Ecofootprint = calculatedecofootprint;
            user.Reductionfromtips = reductionfromtips;

            if (CheckConnection() == NetworkAccess.Internet)
            {
                try
                {
                    await firebaseClient
                    .Child("users")
                    .Child(auth.User.LocalId)
                    .PutAsync(user);
                }
                catch (Exception e)
                {
                    uploaderror = e.ToString();
                }
            }
        }

        public static async Task downloadcountrydata()
        {
            if (CheckConnection() == NetworkAccess.Internet)
            {
                try
                {
                    countryFootprint = await firebaseClient
                        .Child("CountryFootprint")
                        .Child(country)
                        .OnceSingleAsync<CountryFootprint>();
                }
                catch (Exception e)
                {
                    downloadcountryerror = e.ToString();
                    countryFootprint.Country = "0";
                    countryFootprint.CountryEcoFootprint = 0;
                    countryFootprint.CountryReductfromtip = 0;
                    countryFootprint.NumberofUsersofCountry = 1;
                }
            }           
        }

        public static async Task downloadalldata()
        {
            if (CheckConnection() == NetworkAccess.Internet)
            {
                try
                {
                    allFootprint = await firebaseClient
                        .Child("AllFootprint")
                        .OnceSingleAsync<AllFootprint>();
                }
                catch (Exception e)
                {
                    downloadallerror = e.ToString();
                    allFootprint.AllEcoFootprint = 0;
                    allFootprint.AllReductfromtips = 0;
                    allFootprint.NumberofallUser = 1;
                }
            }
        }

        public static void recalculateecofootprint()
        {
            reductionfromtips = Convert.ToDouble(Preferences.Get("reductionfromtips", "0"));
            country = Convert.ToString(Preferences.Get("country", "0"));
            water1 = Convert.ToDouble(Preferences.Get("water1", "0"));
            water2 = Convert.ToDouble(Preferences.Get("water2", "0"));
            water3 = Convert.ToDouble(Preferences.Get("water3", "0"));
            water4 = Convert.ToDouble(Preferences.Get("water4", "0"));
            water5 = Convert.ToDouble(Preferences.Get("water5", "0"));
            water6 = Convert.ToDouble(Preferences.Get("water6", "0"));
            water7 = Convert.ToDouble(Preferences.Get("water7", "0"));
            allwater = water1 + water2 + water3 + water4 + water5 + water6 + water7;
            food1 = Convert.ToDouble(Preferences.Get("food1", "0"));
            food2 = Convert.ToDouble(Preferences.Get("food2", "0"));
            food3 = Convert.ToDouble(Preferences.Get("food3", "0"));
            food4 = Convert.ToDouble(Preferences.Get("food4", "0"));
            food5 = Convert.ToDouble(Preferences.Get("food5", "0"));
            food6 = Convert.ToDouble(Preferences.Get("food6", "0"));
            food7 = Convert.ToDouble(Preferences.Get("food7", "0"));
            allfood = food1 + food2 + food3 + food4 + food5 + food6 + food7;
            transport1 = Convert.ToDouble(Preferences.Get("transport1", "0"));
            transport2 = Convert.ToDouble(Preferences.Get("transport2", "0"));
            transport3 = Convert.ToDouble(Preferences.Get("transport3", "0"));
            transport4 = Convert.ToDouble(Preferences.Get("transport4", "0"));
            transport5 = Convert.ToDouble(Preferences.Get("transport5", "0"));
            transport6 = Convert.ToDouble(Preferences.Get("transport6", "0"));
            alltransport = transport1 + transport2 + transport3 + transport4 + transport5 + transport6;
            shelter1 = Convert.ToDouble(Preferences.Get("shelter1", "0"));
            shelter2 = Convert.ToDouble(Preferences.Get("shelter2", "0"));
            shelter3 = Convert.ToDouble(Preferences.Get("shelter3", "0"));
            allshelter = shelter1 + shelter2 + shelter3;
            energy1 = Convert.ToDouble(Preferences.Get("energy1", "0"));
            energy2 = Convert.ToDouble(Preferences.Get("energy2", "0"));
            energy3 = Convert.ToDouble(Preferences.Get("energy3", "0"));
            energy4 = Convert.ToDouble(Preferences.Get("energy4", "0"));
            energy5 = Convert.ToDouble(Preferences.Get("energy5", "0"));
            energy6 = Convert.ToDouble(Preferences.Get("energy6", "0"));
            energy7 = Convert.ToDouble(Preferences.Get("energy7", "0"));
            allenergy = energy1 + energy2 + energy3 + energy4 + energy5 + energy6 + energy7;
            cloth1 = Convert.ToDouble(Preferences.Get("cloth1", "0"));
            cloth2 = Convert.ToDouble(Preferences.Get("cloth2", "0"));
            cloth3 = Convert.ToDouble(Preferences.Get("cloth3", "0"));
            cloth4 = Convert.ToDouble(Preferences.Get("cloth4", "0"));
            cloth5 = Convert.ToDouble(Preferences.Get("cloth5", "0"));
            cloth6 = Convert.ToDouble(Preferences.Get("cloth6", "0"));
            cloth7 = Convert.ToDouble(Preferences.Get("cloth7", "0"));
            cloth8 = Convert.ToDouble(Preferences.Get("cloth8", "0"));
            allcloth = cloth1 + cloth2 + cloth3 + cloth4 + cloth5 + cloth6 + cloth7 + cloth8;
            waste1 = Convert.ToDouble(Preferences.Get("waste1", "0"));
            waste2 = Convert.ToDouble(Preferences.Get("waste2", "0"));
            waste3 = Convert.ToDouble(Preferences.Get("waste3", "0"));
            waste4 = Convert.ToDouble(Preferences.Get("waste4", "0"));
            waste5 = Convert.ToDouble(Preferences.Get("waste5", "0"));
            waste6 = Convert.ToDouble(Preferences.Get("waste6", "0"));
            waste7 = Convert.ToDouble(Preferences.Get("waste7", "0"));
            allwaste = waste1 + waste2 + waste3 + waste4 + waste5 + waste6 + waste7;
            fun1 = Convert.ToDouble(Preferences.Get("fun1", "0"));
            fun2 = Convert.ToDouble(Preferences.Get("fun2", "0"));
            fun3 = Convert.ToDouble(Preferences.Get("fun3", "0"));
            allfun = fun1 + fun2 + fun3;
            calculatedecofootprint = allwater + allfood + alltransport + allshelter + allenergy + allcloth + allwaste + allfun;
        }

        public static NetworkAccess CheckConnection()
        {
            return Connectivity.NetworkAccess;
        }

        public static void weekoftheyearchecker()
        {
            weekoftheyear = Convert.ToDouble(Preferences.Get("weekoftheyear", "0"));
            double actwoty = Convert.ToDouble(Math.Ceiling((double)(DateTime.Now.DayOfYear / 7)));
            if (weekoftheyear != actwoty)
            {
                Preferences.Set("weekoftheyear", actwoty.ToString());
                weekoftheyearchanged = true;
            }
        }

        public static void daychangedchecker()
        {
            dayoftheyear = Convert.ToDouble(Preferences.Get("dayoftheyear", "0"));
            double actdoty = Convert.ToDouble(DateTime.Now.DayOfYear);
            if (dayoftheyear != actdoty)
            {
                Preferences.Set("dayoftheyear", actdoty.ToString());
                dayoftheyearchanged = true;
            }
        }

        public static void daylyfactpicker()
        {
            daylyfactrow = Int32.Parse(Preferences.Get("daylyfactrow", "0"));
            if (dayoftheyearchanged)
            {
                Random rand = new Random();
                int temp = rand.Next(0, dailyfacts.Count);
                Preferences.Set("daylyfactrow", temp.ToString());
                daylyfactrow = temp;
            }
        }

        public static void tipspicker()
        {
            chosentips = new List<weeklytips>();

            Random rand = new Random();
            if (weekoftheyearchanged)
            {
                int i = 0;
                int[] random = { -1, -1, -1, -1, -1 };

                do
                {
                    int temp = rand.Next(0, weeklytipslist.Count);

                    int drawn = Array.IndexOf(random, temp);

                    if (drawn == -1)
                    {
                        random[i] = temp;
                        i++;
                        Preferences.Set("tip" + i.ToString(), temp.ToString());
                    }
                } while (i < 5);

                chosentips.Clear();
                for (i = 0; i < 5; i++)
                {
                    chosentips.Add(weeklytipslist[random[i]]);
                }

                Preferences.Set("tip1done", 0.ToString());
                Preferences.Set("tip2done", 0.ToString());
                Preferences.Set("tip3done", 0.ToString());
                Preferences.Set("tip4done", 0.ToString());
                Preferences.Set("tip5done", 0.ToString());
            }
            else
            {
                chosentips.Clear();
                for (int i = 1; i < 6; i++)
                {
                    int sor = Int32.Parse(Preferences.Get(("tip" + i.ToString()), "0"));
                    chosentips.Add(weeklytipslist[sor]);
                }
            }
        }

        public static void readjason()
        {
            if (File.Exists(activechallangejson))
            {
                using (var reader = new StreamReader(activechallangejson))
                {
                    string rawfilestring = reader.ReadToEnd();
                    if (rawfilestring != "")
                    {
                        activechallenges = JsonConvert.DeserializeObject<List<activechallenge>>(rawfilestring);
                    }
                }

                if (activechallenges.Count > 0)
                {
                    double challengereduction = Convert.ToDouble(Preferences.Get("challengereduction", "0"));

                    foreach (activechallenge i in activechallenges)
                    {
                        if (dayspassedsincelastlogin > 0)
                        {
                            i.passed_days += dayspassedsincelastlogin;
                            int counter = (int)(i.passed_days / (365 / (int)i.regularity));
                            int oldcounter = i.counter;
                            i.counter = counter > (int)i.regularity ? (int)i.regularity : counter;
                            double reductionchange = (i.counter - oldcounter) * i.task_value;

                            challengereduction += reductionchange;
                            Preferences.Set("challengereduction", challengereduction.ToString());

                            reductionfromtips += reductionchange;
                            reductionfromtips = reductionfromtips >= App.calculatedecofootprint ? App.calculatedecofootprint - App.calculatedecofootprint * 0.1 : reductionfromtips;
                            Preferences.Set("reductionfromtips", reductionfromtips.ToString());
                        }
                        activechallengesO.Add(i);
                    }

                    int finished = Int32.Parse(Preferences.Get("finished", "0"));
                    int deleted = activechallenges.RemoveAll(item => item.counter == (int)item.regularity);
                    finished += deleted;
                    Preferences.Set("finished", finished.ToString());

                    using (var writer = new StreamWriter(activechallangejson))
                    {
                        writer.Write(JsonConvert.SerializeObject(activechallenges));
                    }
                }
            }
            else
            {
                File.Create(activechallangejson);
            }
        }

        public static void dayspassedsincelastlogin_calc()
        {
            DateTime lastlogin = DateTime.Parse(Preferences.Get("lastlogin", DateTime.Now.ToString()));
            dayspassedsincelastlogin = (int)(DateTime.Today - lastlogin.Date).TotalDays;
            Preferences.Set("lastlogin", DateTime.Now.ToString());
        }
    }
}
