package com.application.tak.takapplication.services;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

import com.application.tak.takapplication.actClientTask;
import com.application.tak.takapplication.actFirstUsage;
import com.application.tak.takapplication.actStudentTask;
import com.application.tak.takapplication.data_access.CheckPassword;
import com.application.tak.takapplication.data_access.CheckUsernameExists;
import com.application.tak.takapplication.data_access.Config;
import com.application.tak.takapplication.data_access.CreateClient;
import com.application.tak.takapplication.data_access.CreateStudent;
import com.application.tak.takapplication.data_access.GetUserByUsername;
import com.application.tak.takapplication.data_model.Adress;
import com.application.tak.takapplication.data_model.User;
import com.application.tak.takapplication.interfaces.OnDBRequestFinished;
import com.application.tak.takapplication.local_db.LocalDB;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * Created by azielinska on 28.10.2017.
 */

public class LoginStatus
{
    private Context _ctx;
    CreateClient client;
    CreateStudent student;

    public LoginStatus(Context ctx)
    {
        _ctx = ctx;
    }

    public User IsLoggedIn()
    {
        LocalDB database = new LocalDB(_ctx);

        ArrayList<User> users = database.GetAllUsers();

        User u =null;

        for(User t:users)
        {
            if(t.get_IsLoggedIn() != null && t.get_IsLoggedIn() == 1 && u == null)
            {
                u = t;
            }
        }

        if(u != null)
            return u;
        return null;
    }

    public void LogOut(Activity act)
    {
        LocalDB localDb = new LocalDB(_ctx);
        localDb.LogOutAllUsers();

        Intent i = new Intent(_ctx,actFirstUsage.class);
        act.startActivity(i);
        act.finish();
    }

    public Integer GetUserRole()
    {
        LocalDB database = new LocalDB(_ctx);

        ArrayList<User> users = database.GetAllUsers();
        //Optional<User> loggedIn = users.stream().findFirst();

        User u =null;

        for(User t:users)
        {
            if(u == null)
            {
                u = t;
            }
        }

        if(u != null)
            return u.get_RoleId();
        return null;
    }


    public boolean AreUsersRegistered()
    {
        LocalDB database = new LocalDB(_ctx);

        ArrayList<User> users = database.GetAllUsers();

        if(users.size() > 0)
            return true;
        return false;
    }

    public void NewClient(User u, Adress a, Activity act)
    {
        CreateClient client = new CreateClient(_ctx);
        client.showProgressDialog = false;
        client.setDBRequestFinishedListener(new OnDBRequestFinished() {
            @Override
            public void onDBRequestFinished()
            {
                if(client.newClient != null)
                {
                    Config.LoggedInClient = client.newClient;
                    LocalDB database = new LocalDB(_ctx);
                    User newUser = Config.LoggedInClient;
                    database.LogOutAllUsers();
                    database.AddUser(newUser,1);


                }
            }
        });

       boolean isResultOk = client.InsertClient(u,a);

    }

    public void NewStudent(User u,Activity act)
    {
        student = new CreateStudent(_ctx);
        student.showProgressDialog = false;

        student.setDBRequestFinishedListener(new OnDBRequestFinished() {
            @Override
            public void onDBRequestFinished() {
                if(student.newStudent != null)
                {
                    Config.LoggedInStudent = student.newStudent;
                    LocalDB database = new LocalDB(_ctx);
                    User newUser = Config.LoggedInStudent;
                    database.LogOutAllUsers();
                    database.AddUser(newUser,1);

                    Intent i = new Intent(_ctx,actStudentTask.class);
                    i.addFlags((Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK));
                    act.startActivity(i);
                    act.finish();
                }
                else if(student.dbResult != null)
                {
                    //nastapil problem
                    Toast.makeText(_ctx,student.dbResult.getMSG(),Toast.LENGTH_LONG).show();
                }
            }
        });

        boolean isResultOk = student.InsertStudent(u);
    }

    public void LogInStudent(String id, Activity act)
    {
        try{
        GetUserByUsername getUser = new GetUserByUsername(id,_ctx);

        getUser.setDBRequestFinishedListener(new OnDBRequestFinished() {
            @Override
            public void onDBRequestFinished() {
                if (getUser._student != null) {
                    Config.LoggedInStudent = getUser._student;

                    LocalDB localDB = new LocalDB(_ctx);
                    localDB.LogOutAllUsers();
                    if(localDB.GetUser(Config.LoggedInStudent.get_Id()) == null)
                    {
                        localDB.AddUser(Config.LoggedInStudent,1);
                    }

                    localDB.UpdateUser(Config.LoggedInStudent.get_Id(),1);

                    Intent i = new Intent(_ctx,actStudentTask.class);
                    act.startActivity(i);
                    act.finish();
                }
                else if(getUser.dbResult != null)
                {
                    Toast.makeText(_ctx,"Taki użytkownik nie istnieje jeszcze w bazie danych. Zarejestruj się!",Toast.LENGTH_LONG).show();
                }
            }
        });}
        catch (Exception ex)
        {
            Log.d("ERROR",ex.toString());
        }
    }

    public void LogInClient(User u, Activity act)
    {
        try{
            CheckPassword passCheck= new CheckPassword(_ctx);
            passCheck.showProgressDialog = false;
            passCheck.setDBRequestFinishedListener(new OnDBRequestFinished() {
                @Override
                public void onDBRequestFinished() {
                    if(passCheck._client != null)
                    {
                        Config.LoggedInClient = passCheck._client;
                        LocalDB localdb = new LocalDB(_ctx);
                        localdb.LogOutAllUsers();
                        if(localdb.GetUser(Config.LoggedInClient.get_Id()) == null)
                        {
                            localdb.AddUser(Config.LoggedInClient,1);
                        }
                        localdb.UpdateUser(Config.LoggedInClient.get_Id(),1);
                        Intent i = new Intent(_ctx,actClientTask.class);
                        act.startActivity(i);
                        act.finish();

                    }
                    if(passCheck.dbResult != null)
                    {
                            Toast.makeText(_ctx,passCheck.dbResult.getMSG(), Toast.LENGTH_LONG).show();
                    }
                }
            });
            passCheck.CheckPassword(u,2);
        }
        catch (Exception ex)
        {
            Log.d("ERROR",ex.toString());
        }
    }


}
