<?php

namespace Admin;

use Asset;
use Auth;
use Band;
use Input;
use JuryVote;
use Response;
use Sentry;
use Support\Facades\Contest;
use View;
use Illuminate\Support\Facades\Route;

class JuryVotesController extends \Clumsy\CMS\Controllers\AdminController
{
    protected $ratings = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

    public function juryIndex()
    {
        
        //these queries take on a lot of memory because of the votes that are included the objects...sigh
        
        ini_set('memory_limit','-1');
        
        $group = Sentry::findGroupByName('Users');
        $jury = $group->users->sortBy('id');

        $juryVotesTemplate = [];

        foreach ($jury as $juror) {
            $juryVotesTemplate[$juror->id] = 0;
        }
        $bands = Band::with('votes', 'semiFinalVotes', 'juryVotes')->ofType('approved')->get()->filter(function ($band) {
            return count($band->juryVotes);
        })->map(function ($band) use ($juryVotesTemplate) {

            $juryRatings = $juryVotesTemplate;
            $total = 0;

            foreach ($band->juryVotes as $rating) {
                $total += $rating->rating;
                if (array_key_exists($rating->voter_id, $juryRatings)) {
                    $juryRatings[$rating->voter_id] = $rating->rating;
                }
            }

            $band->juryVotes = $juryRatings;
            $band->totalScore = $total;

            return $band;
        })->sortByDesc('totalScore');

        /*$bandsWithVotes = [
            [
                'id' => ,
                'name' => ,
                'music' =>
                'ratings' => [
                    'EDP' => 10
                ],
                'total' => 100
            ]
        ];
        
        foreach ($bands as $band) {
            $bandsWithVotes
        }*/

        //dd($bands->first()->juryVotes);
        return View::make('admin.jury-votes.jury-list', compact('jury', 'bands'));
    }

    public function jurorBandsRatings($id)
    {
        $juror = Sentry::getUserProvider()->findById($id);

        if (is_null($juror)) {
            return Redirect::back();
        }

        $ratings = JuryVote::where('voter_id', $juror->id)->get();

        return View::make('admin.jury-votes.juror-bands-ratings', compact('ratings', 'juror'));
    }

    public function juryVoting()
    {
        View::share('status', Contest::status());

        Asset::json('jury', array(
            'token' => csrf_token()
        ));

        /*$winner = false;
        $has_shortlist = false;
        $has_finalists = false;

        if (Contest::hasEnded()) {

            $winner = Band::with('votes')->ofType('approved')->where('winner', true)->first();

            if (Contest::getDate('show-finalists')->isPast()) {
                $has_finalists = (bool)Band::ofType('approved')->where('final', true)->first();
            }
        }

        if (Contest::getDate('show-semi-finalists')->isPast() && Band::ofType('approved')->where('shortlist', true)->first()) {
            $has_shortlist = true;
        }

        View::share('winner', $winner);
        View::share('has_shortlist', $has_shortlist);
        View::share('has_finalists', $has_finalists);*/

        //dd(Input::get('selection'));

        $paginate = true; // If pagination is optional, set to false

        $selection = false;

        if (is_null(Input::get('selection'))) {

            $bands = Band::with('votes', 'semiFinalVotes')->ofType('approved');

        } else {
            $bands = Band::where('selected', 1)->with('votes', 'semiFinalVotes')->ofType('approved');
            $selection = true;
        }



        if (Contest::hasEnded()) {

            // If there are finalists, filter only finalists, except when winner has been chosen
            if (Contest::getDate('show-finalists')->isPast() && Band::ofType('approved')->orWhere('final', true)->first()) {
                if (!Band::with('votes')->ofType('approved')->where('winner', true)->first()) {
                    $bands->where('final', true);
                }
            } else {
                $bands->where('shortlist', true);
            }
        } elseif (Contest::getDate('show-semi-finalists')->isPast()) {

            // If shortlist has been created, filter only shortlist entries
            if (Band::ofType('approved')->where('shortlist', true)->first()) {
                $bands->where('shortlist', true);
            }
        } else {
            $paginate = true;
        }

        $bands->orderBy('name', 'asc');

        $queryString = is_null(Input::get('selection')) ? [] : ['selection' => 1];
        
//        $editionName = Contest::editionName();
//        dd($editionName);
        
        $bands = $paginate ? $bands->paginate(10)->appends($queryString) : $bands->get();
        if ($paginate){
            $route = (Route::getCurrentRoute()->getName());

        $bands->setBaseUrl(route($route));
        }
        
        $ratings = $this->ratings;

        $user = Sentry::getUser();

        return View::make('admin.jury-votes.ratings', compact('bands', 'paginate', 'ratings', 'user', 'selection'));
    }

    public function postJuryVoting($id)
    {
        $user = Sentry::getUser();
        $band = Band::find($id);
        $rating = Input::get('rating');

        if (is_null($band)) {
            return Response::json(array(
                'status' => 404,
                'error'  => 'Band not found'
            ));
        }

        $vote = JuryVote::where('band_id', $id)
                    ->where('voter_id', $user->id)
                    ->first();

        if (is_null($vote)) {
            $vote = new JuryVote;
        }

        $vote->voter_id = $user->id;
        $vote->band_id = $band->id;
        $vote->rating = $rating;

        $vote->save();

        return Response::json(array(
            'status' => 200,
            'error'  => 'Feito!'
        ));

    }
}