package wad.config;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configurers.GlobalAuthenticationConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import wad.domain.Account;
import wad.domain.Player;
import wad.domain.Series;
import wad.domain.Team;
import wad.domain.Tournament;
import wad.repository.AccountRepository;
import wad.repository.PlayerRepository;
import wad.repository.SeriesRepository;
import wad.repository.TeamRepository;
import wad.repository.TournamentRepository;
import wad.service.TeamService;
import wad.service.TournamentService;
import wad.util.SeriesGenerator;

@Profile("default")
@Configuration
@EnableWebSecurity
public class DefaultSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private TournamentService tournamentService;
    @Autowired
    private TeamService teamService;
    @Autowired
    private SeriesRepository seriesRepository;
    @Autowired
    private PlayerRepository playerRepository;
    @Autowired
    private AccountRepository accountRepository;
    
    private boolean ekaKerta;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // sallitaan h2-konsolin käyttö
        http.csrf().disable();
        http.headers().frameOptions().sameOrigin();

        http.authorizeRequests()
                .anyRequest().permitAll();

        http
                .formLogin()
                .loginPage("/login.html")
                .failureUrl("/login-error.html")
                .and()
                .logout()
                .logoutSuccessUrl("/tournaments.html");
        testingStuff();
    }

    @Configuration
    protected static class AuthenticationConfiguration extends GlobalAuthenticationConfigurerAdapter {

        @Autowired
        private JpaAuthenticationProvider jpaAuthenticationProvider;

        @Override
        public void init(AuthenticationManagerBuilder auth) throws Exception {
            auth.authenticationProvider(jpaAuthenticationProvider);
        }
    }

//    @Autowired
//    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
//        auth.inMemoryAuthentication()
//                .withUser("jack").password("bauer").roles("USER");
//    }
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    public void testingStuff() {
        if (ekaKerta == false) {
            Account account = new Account();
            account.setUsername("admin");
            account.setPassword("password");
            accountRepository.save(account);
            tournamentService.deleteAll();
            Tournament testi = new Tournament();
            testi.setName("Turnaus");
            testi.setDate(new Date());
            Team eka = new Team();
            Team toka = new Team();
            Team kolmas = new Team();
            Team neljas = new Team();
            eka.setName("ekatiimi");
            toka.setName("tokatiimi");
            kolmas.setName("kolmastiimis");
            neljas.setName("neljastiimi");
            tournamentService.save(testi);

            List<Team> teams = saveTestPlayers(eka, toka, kolmas, neljas, testi);
            testi.setTeams(teams);

            SeriesGenerator seriesGenerator = new SeriesGenerator();
            List<Series> series = seriesGenerator.generate(tournamentService.findByName("Turnaus"), teams);
            Collections.sort(series);
            for (Series serie : series) {
                seriesRepository.save(serie);
            }
            ekaKerta = true;
        }
    }

    public List<Team> saveTestPlayers(Team eka, Team toka, Team kolmas, Team neljas, Tournament testi) {

        eka.setTournament(testi);
        toka.setTournament(testi);
        kolmas.setTournament(testi);
        neljas.setTournament(testi);
//        teamService.save(eka);
//        teamService.save(toka);
//        teamService.save(kolmas);
//        teamService.save(neljas);
//        Player pekka = new Player();
//        pekka.setName("pekka");
////        playerRepository.save(pekka);
//        Player heikki = new Player("heikki");
////        playerRepository.save(heikki);
//        Player seppo = new Player("seppo");
////        playerRepository.save(seppo);
//        eka.setPlayers(Arrays.asList(pekka, heikki, seppo));
//
//        Player marjatta = new Player("marjatta");
////        playerRepository.save(marjatta);
//        Player sirkka = new Player("sirkka");
////        playerRepository.save(sirkka);
//        Player sirpa = new Player("sirpa");
////        playerRepository.save(sirpa);
//        toka.setPlayers(Arrays.asList(marjatta, sirkka, sirpa));
//
//        Player rommel = new Player("rommel");
////        playerRepository.save(rommel);
//        Player patton = new Player("patton");
////        playerRepository.save(patton);
//        Player mannerheim = new Player("mannerheim");
////        playerRepository.save(mannerheim);
//        kolmas.setPlayers(Arrays.asList(rommel, patton, mannerheim));
//
//        Player saara = new Player("saara");
////        playerRepository.save(saara);
//        Player tom = new Player("tom");
////        playerRepository.save(tom);
//        Player jerry = new Player("jerry");
////        playerRepository.save(jerry);
//        neljas.setPlayers(Arrays.asList(saara, tom, jerry));
        eka.setPlayersString("pekka");
        toka.setPlayersString("sirpa");
        kolmas.setPlayersString("rommel");
        neljas.setPlayersString("saara");
        tournamentService.addTeam(eka, "Turnaus");
        tournamentService.addTeam(toka, "Turnaus");
        tournamentService.addTeam(kolmas, "Turnaus");
        tournamentService.addTeam(neljas, "Turnaus");
        List<Team> teams = new ArrayList<>();
        teams.addAll(tournamentService.findAllTeams("Turnaus"));
        return teams;
    }

}
