<?php namespace Eae\Command;

use Carbon\Carbon;
use Illuminate\Console\Command;
use EventItem;
use DB;


class ExportEventsCommand extends Command
{

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'cronologias:export-events';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Export DB.';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function fire()
    {
        $now = Carbon::now()->format('YmdHis');

        $filename = storage_path("events-export-{$now}.csv");
        $file = fopen($filename, 'w');

        if ($file === false) {
            die('Error opening the file '.$filename);
        }

        fputs($file, (chr(0xEF).chr(0xBB).chr(0xBF))); // support unicode

        $headerRow = [
            'id', 'hide_day', 'hide_month', 'decade', 'is_year', 'is_decade',
            'event_type', 'content', 'area', 'embed',
            'main_image_file_name', 'main_image_author'
        ];

        $maxEventDates = DB::table('event_dates')->selectRaw('COUNT(1) as counter')
            ->groupBy('event_item_id')->orderBy('counter', 'desc')
            ->first();
        $maxEventDates = $maxEventDates->counter;

        for ($i = 1; $i <= $maxEventDates; $i++) {
            $headerRow[] = "event_start_date_{$i}";
            $headerRow[] = "event_end_date_{$i}";
        }

        $maxEventMedias = DB::table('event_medias')->selectRaw('COUNT(1) as counter')
            ->groupBy('event_item_id')->orderBy('counter', 'desc')
            ->first();
        $maxEventMedias = $maxEventMedias->counter;

        for ($i = 1; $i <= $maxEventMedias; $i++) {
            $headerRow[] = "media_{$i}_embed";
            $headerRow[] = "media_{$i}_type";
            $headerRow[] = "media_{$i}_image_file_name";
            $headerRow[] = "media_{$i}_image_author";
        }

        $maxLocations = DB::table('event_item_location')->selectRaw('COUNT(1) as counter')
            ->groupBy('event_item_id')->orderBy('counter', 'desc')
            ->first();
        $maxLocations = $maxLocations->counter;

        for ($i = 1; $i <= $maxLocations; $i++) {
            $headerRow[] = "location_{$i}";
        }

        fputcsv($file, $headerRow);

        EventItem::full()->with(
            [
                'eventDates' => function ($query) {
                    $query->full()->select('*');
                },
                'locations'  => function ($query) {
                    $query->full()->select('*');
                },
                'area'       => function ($query) {
                    $query->full()->select('*');
                },
                'image',
                'eventMedias'       => function ($query) {
                    $query->full()->select('*')->with('mediaImage');
                }
            ]
        )->chunk(
            500,
            function ($eventItems) use ($file, $maxEventDates, $maxLocations, $maxEventMedias) {
                foreach ($eventItems as $eventItem) {
                    $maxEventDatesCounter = $maxEventDates;
                    $maxLocationsCounter = $maxLocations;
                    $maxEventMediasCounter = $maxEventMedias;
                    $row = [
                        $eventItem->id,
                        $eventItem->hide_day,
                        $eventItem->hide_month,
                        $eventItem->decade,
                        $eventItem->is_year,
                        $eventItem->is_decade,
                        $eventItem->event_type,
                        $eventItem->content,
                        $eventItem->area->title,
                        $eventItem->embed
                    ];

                    if (!is_null($eventItem->image)) {
                        $row[] = $eventItem->image->filename;
                        $row[] = $eventItem->image->author;
                    } else {
                        $row[] = null;
                        $row[] = null;
                    }

                    foreach ($eventItem->eventDates as $eventDate) {
                        $row[] = $this->_getDateFormat($eventDate->start_date);
                        $row[] = $this->_getDateFormat($eventDate->end_date);
                        $maxEventDatesCounter--;
                    }
                    if ($maxEventDatesCounter > 0) {
                        for ($i = $maxEventDatesCounter; $i > 0; $i--) {
                            $row[] = null;
                            $row[] = null;
                        }
                    }

                    foreach ($eventItem->eventMedias as $eventMedia) {
                        $row[] = $eventMedia->media_embed;
                        $row[] = $eventMedia->media_type;

                        if(!is_null($eventMedia->mediaImage)) {
                            $row[] = $eventMedia->mediaImage->filename;
                            $row[] = $eventMedia->mediaImage->author;
                        } else {
                            $row[] = null;
                            $row[] = null;
                        }

                        $maxEventMediasCounter--;
                    }
                    if ($maxEventMediasCounter > 0) {
                        for ($i = $maxEventMediasCounter; $i > 0; $i--) {
                            $row[] = null;
                            $row[] = null;
                            $row[] = null;
                            $row[] = null;
                        }
                    }

                    foreach ($eventItem->locations as $location) {
                        $row[] = $location->title;
                        $maxLocationsCounter--;
                    }
                    if ($maxLocationsCounter > 0) {
                        for ($i = $maxLocationsCounter; $i > 0; $i--) {
                            $row[] = null;
                        }
                    }

                    fputcsv($file, $row);
                }


            });

        fclose($file);
    }

    protected function _getDateFormat($date)
    {
        if (is_null($date)) {
            return null;
        }

        return $date->format('Y-m-d');
    }

    /**
     * Get the console command arguments.
     *
     * @return array
     */
    protected function getArguments()
    {
        return array();
    }

    /**
     * Get the console command options.
     *
     * @return array
     */
    protected function getOptions()
    {
        return array();
    }

}
