<?php


class ImportController extends Controller{
    private $mediaItems = null;
    private $locations = null;
    private $areas = null;
    
    public function getIndex(){
        DB::beginTransaction();

        try {
            $this->getPersons();
            $this->getKeywords();
            $this->getAreas();
            $this->getLocations();
            $this->getPhotos();
            $this->getEvents();
            DB::commit();
        } catch (Exception $e) {
            DB::rollBack();
            throw($e);
        }    
    }

    public function getFixLongText(){
        DB::beginTransaction();

        try{
            $contents = DB::table("import")
                ->select("texto")
                ->get();
            header("Content-Type:text/html; charset=UTF-8");
            foreach($contents as $content){
                DB::statement("update event_items_lang
                            set event_items_lang.content = ?
                            where event_items_lang.content like ?",
                    array(
                        $content->texto,
                        '%'.substr($content->texto, 0, 350).'%'
                    )
                );
            }
            echo '<pre>';
            print_r(last(DB::getQueryLog()));
            DB::commit();
        }catch(Exception $e){
            DB::rollBack();
            throw($e);
        }
    }

    public function getUpdateLocations(){
        DB::beginTransaction();
        header("Content-Type:text/html; charset=UTF-8");
    
        try{
            DB::statement("INSERT IGNORE INTO event_item_location(event_item_id, location_id) 
                SELECT id, location_id FROM event_items WHERE location_id IS NOT NULL"); 
                
            $csvLocations = DB::table("import_locations")->get();
            foreach($csvLocations as $csvLocation){
                $locations = explode(",",$csvLocation->title);
                $originalId = $csvLocation->location_id;
                $newIds = array(); 
                foreach($locations as $location){
                    $name = trim($location);

                    if(empty($name)){
                        continue;
                    }
                    
                    $dbLocation = new Location();
                    $dbLocation->save();
                    $newIds[] = $dbLocation->id;
                    DB::statement("insert into locations_lang (location_id,language_id,title)
                        values(?, ?, ?)",
                        array(
                            $dbLocation->id,
                            'pt',
                            $name
                        )
                    );

                    DB::statement("insert into website_objects (object_id, object_type, content_type, slug, status)
                        values(?, ?, ?, ?, ?)",
                        array(
                            $dbLocation->id,
                            get_class($dbLocation),
                            "location",
                            $this->_generateSlug($name),
                            "published"
                        )
                    );    
                } 
  
                foreach($newIds as $newId){
                    DB::statement("INSERT INTO event_item_location(event_item_id, location_id) 
                        SELECT event_item_id, ? FROM event_item_location WHERE location_id = ?",
                        array($newId, $originalId));     
                }                    
            }
            
            DB::statement("DELETE FROM locations 
                WHERE id IN (SELECT location_id FROM import_locations)");       
            DB::statement("DELETE FROM website_objects 
                WHERE object_id IN (SELECT location_id FROM import_locations) 
                AND object_type = ?" , 
                array(get_class(new Location())));       
            
            $csvDuplicates = DB::table("locations_lang")
                ->selectRaw("group_concat(location_id) as csv")
                ->groupBy("title")
                ->havingRaw("count(location_id) > 1")
                ->get();
            
            foreach($csvDuplicates as $csvDuplicate){
                $locationIds = explode(",",$csvDuplicate->csv);
                $deleteIds = array();
                $mainId = null;    
                foreach($locationIds as $locationId){
                    if(is_null($mainId)){
                        $mainId = $locationId;    
                    }else{
                        $deleteIds[] = $locationId;    
                    }
                    
                    
                }
                
                DB::statement("UPDATE IGNORE event_item_location 
                    SET location_id = {$mainId} 
                    WHERE location_id IN (" . implode(",", $deleteIds) . ")");
            }
            
            DB::statement("DELETE FROM locations 
                WHERE id NOT IN (SELECT location_id FROM event_item_location)");
            
            DB::statement("DELETE FROM website_objects 
                WHERE object_id NOT IN (SELECT id FROM locations) 
                AND object_type = ?" , 
                array(get_class(new Location())));
 
            DB::commit();        
        }catch(Exception $e){
            DB::rollBack();
            throw($e);
        }
        
    
    }

    public function getCountDateErrors() {
        $events = DB::table("import")->whereRaw("trim(area) != '' AND trim(ano) != ''")->get();
        $count = 0;
        foreach($events as $event){
            try {
                $title = $this->_getStartDate($event);
                $this->_getEventDatesCollection($event);
            }
            catch(Exception $e) {
                $count++;
            }
        }
        echo $count;
    }
    
    public function getPersons(){
        DB::beginTransaction();
        
        try{
            DB::statement("update import set personagem = replace(personagem, '\n', ' ')");
            DB::statement("update import set personagem = replace(personagem, ' ', '')");
            $persons = DB::table("import")->selectRaw("distinct(trim(personagem)) as names")
                ->whereRaw("trim(personagem) != ''")
                ->orderByRaw("trim(personagem) asc")
                ->get();
            header("Content-Type:text/html; charset=UTF-8");
            $dbPersons = DB::table("people_lang")->select("title")->get();
           
            $insertedNames = array_map(function($dbPerson){
                return strtolower($dbPerson->title);        
            },$dbPersons);
            $dbPersons = null;
            foreach($persons as $person){
                $names = explode(",",$person->names);
                foreach($names as $name){
                    $name = trim($name);

                    if(empty($name)){
                        continue;
                    }
                    if(in_array(strtolower($name), $insertedNames)){
                        continue;
                    }

                    $insertedNames[] = strtolower($name);
                    $dbPerson = new Person();
                    $dbPerson->is_featured = 0;
                    $dbPerson->save();
                    DB::statement("insert into people_lang (person_id,language_id,title)
                        values(?, ?, ?)",
                        array(
                            $dbPerson->id,
                            'pt',
                            $name
                        )
                    );

                    DB::statement("insert into website_objects (object_id, object_type, content_type, slug, status)
                        values(?, ?, ?, ?, ?)",
                        array(
                            $dbPerson->id,
                            get_class($dbPerson),
                            "person",
                            $this->_generateSlug($name),
                            "published"
                        )
                    );
                }
                    
            }

            DB::commit();        
        }catch(Exception $e){
            DB::rollBack();
            throw($e);
        }            
    }

    public function getKeywords(){
        DB::beginTransaction();
        
        try{
            DB::statement("update import set palavras_chave = replace(palavras_chave, '\n', ' ')");
            DB::statement("update import set palavras_chave = replace(palavras_chave, ' ', '')");
            $keywords = DB::table("import")->selectRaw("distinct(trim(palavras_chave)) as names")
                ->whereRaw("trim(palavras_chave) != ''")
                ->orderByRaw("trim(palavras_chave) asc")
                ->get();
            header("Content-Type:text/html; charset=UTF-8");
            $dbKeywords = DB::table("keywords_lang")->select("title")->get();
           
            $insertedKeywords = array_map(function($dbKeyword){
                return strtolower($dbKeyword->title);        
            },$dbKeywords);
            $dbKeywords = null;
            foreach($keywords as $keyword){
                $names = explode(",",$keyword->names); 
                foreach($names as $name){
                    $name = trim($name);
                    
                    if(empty($name)){
                        continue;
                    }
                    if(in_array(strtolower($name), $insertedKeywords)){
                        continue;    
                    }
                    
                    $insertedKeywords[] = strtolower($name);
                    $dbKeyword = new Keyword();
                    $dbKeyword->save();
                    DB::statement("insert into keywords_lang (keyword_id,language_id,title) 
                        values(?, ?, ?)", 
                        array(
                            $dbKeyword->id,
                            'pt',
                            $name
                        )
                    );
  
                    DB::statement("insert into website_objects (object_id, object_type, content_type, slug, status) 
                        values(?, ?, ?, ?, ?)",
                        array(
                            $dbKeyword->id,
                            get_class($dbKeyword),
                            "keyword",
                            $this->_generateSlug($name),
                            "published"    
                        )
                    );
                }
                    
            }

            DB::commit();        
        }catch(Exception $e){
            DB::rollBack();
            throw($e);
        }
    }

    public function getAreas(){
        DB::beginTransaction();

        try {
            DB::statement("update import set area = replace(area, '\n', ' ')");
            DB::statement("update import set area = replace(area, ' ', '')");
            $areas = DB::table("import")->selectRaw("distinct(trim(area)) as area")
                ->whereRaw("trim(area) != ''")
                ->orderByRaw("trim(area) asc")
                ->get();
            header("Content-Type:text/html; charset=UTF-8");
            $dbAreas = DB::table("areas_lang")->select("title")->get();

            $insertedNames = array_map(function ($dbArea) {
                return strtolower($dbArea->title);
            }, $dbAreas);
            $dbAreas = null;
            foreach ($areas as $area) {
                $name = $area->area;
                $name = trim($name);

                if (empty($name)) {
                    continue;
                }
                if (in_array(strtolower($name), $insertedNames)) {
                    continue;
                }

                $insertedNames[] = strtolower($name);
                $dbArea = new Area();
                $dbArea->save();
                DB::statement("insert into areas_lang (area_id,language_id,title)
                    values(?, ?, ?)",
                    array(
                        $dbArea->id,
                        'pt',
                        $name
                    )
                );

                DB::statement("insert into website_objects (object_id, object_type, content_type, slug, status)
                    values(?, ?, ?, ?, ?)",
                    array(
                        $dbArea->id,
                        get_class($dbArea),
                        "area",
                        $this->_generateSlug($name),
                        "published"
                    )
                );


            }

            DB::commit();
        } catch (Exception $e) {
            DB::rollBack();
            throw($e);
        }
    }

    public function getLocations()
    {
        DB::beginTransaction();

        try {
            DB::statement("update import set localidade = replace(localidade, '\n', ' ')");
            DB::statement("update import set localidade = replace(localidade, ' ', '')");
            $localidades = DB::table("import")->selectRaw("distinct(trim(localidade)) as localidade")
                ->whereRaw("trim(localidade) != ''")
                ->orderByRaw("trim(localidade) asc")
                ->get();
            header("Content-Type:text/html; charset=UTF-8");
            $dbLocations = DB::table("locations_lang")->select("title")->get();

            $insertedNames = array_map(function ($dbLocation) {
                return strtolower($dbLocation->title);
            }, $dbLocations);
            $dbLocations = null;
            foreach ($localidades as $localidade) {
                $name = $localidade->localidade;
                $name = trim($name);

                if (empty($name)) {
                    continue;
                }
                if (in_array(strtolower($name), $insertedNames)) {
                    continue;
                }

                $insertedNames[] = strtolower($name);
                $dbLocation = new Location();
                $dbLocation->save();
                DB::statement("insert into locations_lang (location_id,language_id,title)
                    values(?, ?, ?)",
                    array(
                        $dbLocation->id,
                        'pt',
                        $name
                    )
                );

                DB::statement("insert into website_objects (object_id, object_type, content_type, slug, status)
                    values(?, ?, ?, ?, ?)",
                    array(
                        $dbLocation->id,
                        get_class($dbLocation),
                        "location",
                        $this->_generateSlug($name),
                        "published"
                    )
                );
            }

            DB::commit();
        } catch (Exception $e) {
            DB::rollBack();
            throw($e);
        }
    }
    
    public function getPhotos(){
        DB::beginTransaction();
        
        try{
            $photos = DB::table("import")->selectRaw("distinct(trim(foto)) as names")
                ->whereRaw("trim(foto) != ''")
                ->get();
            header("Content-Type:text/html; charset=UTF-8");
            $dbPhotos = DB::table("media_items")->select("filename")->get();
           
            $insertedPhotos = array_map(function($dbPhotos){
                return strtolower($dbPhotos->filename);        
            },$dbPhotos);
            $dbPersons = null;
            
            foreach($photos as $photo){
                $names =  preg_split( "/(,|;)/", trim($photo->names) ); 
                foreach($names as $name){
                    $name = trim($name);
                    
                    if(empty($name)){
                        continue;
                    }
                    if(in_array(strtolower($name), $insertedPhotos)){
                        continue;    
                    }
                    
                    $insertedPhotos[] = strtolower($name);
                    $dbMedia = new MediaItem();
                    $dbMedia->filename = $name;
                    $dbMedia->original_filename = $name;
                    $dbMedia->extension = pathinfo($name, PATHINFO_EXTENSION);
                    $dbMedia->media_type = "image"; 
                    $dbMedia->backend_user_id = 1;
          
                    $destinationPath = Config::get("path.internal.media");
                    try {
                        $img = Image::make($destinationPath . '/' . $name);
                    } catch(Exception $e) {
                        throw new Exception("image source not readable - " . $destinationPath . '/' . $name);
                    }

                    $dbMedia->width = $img->width();
                    $dbMedia->height = $img->height();
                    $img->fit(200, 200);
                    $img->save(Config::get('path.internal.thumbs') . '/' . getFileNameSize($name, '200x200'));
                    $dbMedia->save();
                }
                    
            }
            DB::commit();
            
        }catch(Exception $e){
            DB::rollBack();
            throw($e);    
        }            
    }
    
    public function getEvents(){
        DB::beginTransaction();

        try{
            $events = DB::table("import")->whereRaw("trim(area) != '' AND trim(ano) != ''")->get();
            header("Content-Type:text/html; charset=UTF-8");
           
            foreach($events as $event){
                $dbEvent = new EventItem();
                try {
                    $title = $this->_getStartDate($event);
                }
                catch(Exception $e) {
                    throw new Exception('Invalid date on id ' . $event->id  . ' - ano(' . $event->ano . ') - mes(' . $event->mes . ') - dia ( ' . $event->dia . ') - mes2 ('.$event->mes2.') - dia2('. $event->dia2 . ')' );
                }

                if(empty($title)){
                    continue;   
                }
                
                $title = $title->format("d-m-Y"); 

                $dbEvent->area_id = $this->_getAreaId($event->area);
//                $dbEvent->location_id = $this->_getLocationId($event->localidade);
                $dbEvent->is_map = trim($event->destaque_mapa) == "ok" ? true : false;
                $dbEvent->is_decade = trim($event->destaque_decada) == "ok" ? true : false;
                $dbEvent->is_year = trim($event->destaque_ano) == "ok" ? true : false;
                $dbEvent->hide_day = empty($event->dia);
                $dbEvent->hide_month = empty($event->mes);
                $dbEvent->decade = $this->_getDecade($event);
                $dbEvent->event_type = $this->_getEventType($event);
                
                if($dbEvent->isImage()){
                    $dbEvent->image_id = $this->_getEventMedia($event);
                }elseif($dbEvent->isVideo() || $dbEvent->isAudio()){
                    $dbEvent->embed = $this->_getEventMedia($event);
                }
                
                $dbEvent->save();
                
                $title = $title . "-" . $dbEvent->id;
                
                DB::statement("insert into event_items_lang (event_item_id,language_id,title,content)
                    values(?, ?, ?, ?)",
                    array(
                        $dbEvent->id,
                        'pt',
                        $title,
                        $event->texto
                    )
                );

                DB::statement("insert into website_objects (object_id, object_type, content_type, slug, status)
                    values(?, ?, ?, ?, ?)",
                    array(
                        $dbEvent->id,
                        get_class($dbEvent),
                        "event_item",
                        $this->_generateSlug($title),
                        "published"
                    )
                );

                $this->_setEventMedia($dbEvent, $event);
                try {
                    $this->_setEventDates($dbEvent, $event);
                }
                catch(Exception $e) {
                    throw new Exception('Invalid date on id ' . $event->id  . ' - ano(' . $event->ano . ') - mes(' . $event->mes . ') - dia ( ' . $event->dia . ') - mes2 ('.$event->mes2.') - dia2('. $event->dia2 . ')' );
                }
                $this->_setPeopleIds($dbEvent->id, $event->personagem);
                $this->_setKeywordsIds($dbEvent->id, $event->palavras_chave);
                $this->_setLocationsIds($dbEvent->id, $event->localidade);
            }

            DB::commit();        
        }catch(Exception $e){
            DB::rollBack();

            throw($e);
        }    
    }
    
    public function getSearchAutocomplete(){
        $searchTerm = Input::get("search");
        
        $titulos = DB::table("keywords_lang")->select("title")
            ->where("title", 'like', $searchTerm . "%")
            ->orderByRaw("CHAR_LENGTH(title) asc")
            ->limit(6)
            ->get();
        
        var_dump($titulos);
        
    }
    
    public function getSearchEvents(){
        header("Content-Type:text/html; charset=UTF-8");
        $searchTerm = Input::get("search");
        $dbSearchTerm = Formatter::transformItem($searchTerm, "strip_tags|xss_clean|trim");
        $dbSearchTerm = fulltext_search_term($dbSearchTerm,false,false);
        DB::connection()->flushQueryLog();
        DB::connection()
                ->getPaginator()->setCurrentPage(1);
        $query = EventItem::full()->with("image", "area")
            ->selectRaw("*, min(event_dates.start_date) as min_start_date")
            ->join("event_dates", "event_items.id", "=", "event_dates.event_item_id")
            ->orderBy("min_start_date", "asc")
            ->groupBy("event_items.id");
            
        if(!empty($dbSearchTerm)){
            $query->whereRaw("MATCH(event_items_lang.content) AGAINST (? IN BOOLEAN MODE)", array($dbSearchTerm));
        }    

        $results = $query->paginate(20);     
  
        var_dump($results->getLastPage());
        var_dump($results->getTotal());
        var_dump($results->getCollection()->toArray());
                
    }
    
    private function _setEventDates(EventItem $dbEvent, $event){
        
        $collection = $this->_getEventDatesCollection($event, $dbEvent->id);

        
        foreach($collection as $eventDate){
            $eventDate->save();
            $title = $eventDate->start_date->format("d-m-Y");
            DB::statement("insert into event_dates_lang (event_date_id,language_id,title)
                values(?, ?, ?)",
                array(
                    $eventDate->id,
                    'pt',
                    $title
                )
            );
      
            DB::statement("insert into website_objects (object_id, object_type, content_type, slug, status)
                values(?, ?, ?, ?, ?)",
                array(
                    $eventDate->id,
                    get_class($eventDate),
                    "event_date",
                    $this->_generateSlug($dbEvent->id . "-" .$title),
                    "published"
                )
            );
            
                    
        }
        

        
    }

    private function _getEventDatesCollection($event, $dbEventID = null ) {
        $collection = with(new EventDate())->newCollection();
        $importYear = trim($event->ano);
        $importMonth = trim($event->mes);
        $importDay = trim($event->dia);
        $importMonth2 = trim($event->mes2);
        $importDay2 = trim($event->dia2);
        $intervalType = "single";
        if(strtolower(trim($event->juncao)) == "a"){
            $intervalType = "range";
        }

        if(empty($importYear)){
            throw new Exception("O evento import {$event->id} não tem ano");
        }

        if(!empty($importDay) && empty($importMonth)){
            throw new Exception("O evento import {$event->id} tem dia mas não tem mês");
        }

        if(!empty($importDay2) && empty($importDay)){
            throw new Exception("O evento import {$event->id} tem dia2 mas não dia");
        }

        if(!empty($importDay2) && empty($importMonth2) && empty($importMonth)){
            throw new Exception("O evento import {$event->id} tem dia2 mas não tem mês nem mês2");
        }

        if(!empty($importMonth) && strpos($importMonth, ",") !== false && !empty($importMonth2)){
            throw new Exception("O evento import {$event->id} tem mes com várias entradas e o mes2 está preenchido");
        }

        if(!empty($importMonth) && strpos($importMonth, ",") !== false && (!empty($importDay2) || !empty($importDay))){
            throw new Exception("O evento import {$event->id} tem mes com várias entradas e os dias estão preenchidos");
        }

        if(!empty($importMonth2) && strpos($importMonth2, ",") !== false){
            throw new Exception("O evento import {$event->id} tem mes2 com várias entradas");
        }

        if(!empty($importDay) && !empty($importMonth) && !empty($importDay2)){
            $days = explode(",", $importDay);
            $endDays = explode(",", $importDay2);
            $months = explode(",", $importMonth);

            if(!empty($importMonth2)){
                $endMonth = $importMonth2;
            }else{
                $endMonth = last($months);
            }

            if(sizeOf($days) > 1 || sizeOf($endDays) > 1 || $intervalType == "single"){
                foreach($days as $day){
                    $eventDate = $this->_getSingleEventDate(trim($day),trim(head($months)),$importYear);
                    $eventDate->event_item_id = $dbEventID;
                    $collection->add($eventDate);
                }

                foreach($endDays as $endDay){
                    $eventDate = $this->_getSingleEventDate(trim($endDay),trim($endMonth),$importYear);
                    $eventDate->event_item_id = $dbEventID;
                    $collection->add($eventDate);
                }
            }else{
                $eventDate = $this->_getIntervalEventDate(trim($days[0]),trim(head($months)),$importYear,trim($endDays[0]),trim($endMonth));
                $eventDate->event_item_id = $dbEventID;
                $collection->add($eventDate);
            }
        }elseif(!empty($importDay) && !empty($importMonth)){
            $days = explode(",", $importDay);
            $months = explode(",", $importMonth);


            foreach($days as $day){
                $eventDate = $this->_getSingleEventDate(trim($day),trim(head($months)),$importYear);
                $eventDate->event_item_id = $dbEventID;
                $collection->add($eventDate);
            }

        }elseif(!empty($importMonth)){
            $months = explode(",", $importMonth);

            if(sizeof($months) > 1){
                foreach($months as $month){
                    $month = trim($month);
                    $monthNumber = $this->_getMonth($month);

                    $endDate = db_date_to_carbon("{$importYear}-{$monthNumber}-01");
                    $endDate->modify("last day of this month");
                    $eventDate = $this->_getIntervalEventDate('1',$month,$importYear,$endDate->day,$month);
                    $eventDate->event_item_id = $dbEventID;
                    $collection->add($eventDate);
                }
            }else{
                $month = trim($months[0]);
                if(!empty($importMonth2)){
                    $endMonth = trim($importMonth2);
                }else{
                    $endMonth = $month;
                }

                if($endMonth == $month || $intervalType == "range"){

                    $endMonthNumber = $this->_getMonth($endMonth);
                    $endDate = db_date_to_carbon("{$importYear}-{$endMonthNumber}-01");
                    $endDate->modify("last day of this month");
                    $eventDate = $this->_getIntervalEventDate('1',$month,$importYear,$endDate->day,$endMonth);
                    $eventDate->event_item_id = $dbEventID;
                    $collection->add($eventDate);
                }else{
                    $startMonthNumber = $this->_getMonth($month);
                    $startDate = db_date_to_carbon("{$importYear}-{$startMonthNumber}-01");
                    $startDate->modify("last day of this month");
                    $eventDate = $this->_getIntervalEventDate('1',$month,$importYear,$startDate->day,$month);
                    $eventDate->event_item_id = $dbEventID;
                    $collection->add($eventDate);

                    $endMonthNumber = $this->_getMonth($endMonth);
                    $endDate = db_date_to_carbon("{$importYear}-{$endMonthNumber}-01");
                    $endDate->modify("last day of this month");
                    $eventDate = $this->_getIntervalEventDate('1',$endMonth,$importYear,$endDate->day,$endMonth);
                    $eventDate->event_item_id = $dbEventID;
                    $collection->add($eventDate);
                }
            }

        }else{
            $eventDate = $this->_getIntervalEventDate('1',"Janeiro",$importYear,"31","Dezembro");
            $eventDate->event_item_id = $dbEventID;
            $collection->add($eventDate);
        }

        return $collection;
    }
    
    private function _getSingleEventDate($day, $month, $year){
        $date = new EventDate();
        $month = $this->_getMonth($month);
        $date->start_date = db_date_to_carbon("{$year}-{$month}-{$day}");
        return $date;    
               
    }
    
    private function _getIntervalEventDate($day, $month, $year, $day2, $month2){
        $date = new EventDate();
        $month = $this->_getMonth($month);
        $month2 = $this->_getMonth($month2);
        $date->start_date = db_date_to_carbon("{$year}-{$month}-{$day}");
        $date->end_date = db_date_to_carbon("{$year}-{$month2}-{$day2}");
        return $date;    
               
    }
    
    private function _getDecade($event){
        if($event->decada == "1960-1969"){
            return 1960;
        }elseif($event->decada == "1970-1979"){
            return 1970;
        }elseif($event->decada == "1980-1989"){
            return 1980;
        }elseif($event->decada == "1990-1999"){
            return 1990;
        }elseif($event->decada == "2000-2009"){
            return 2000;
        }elseif($event->decada == "2010-2019"){
            return 2010;
        }elseif($event->decada == "2000-2016"){
            return 2000;
        }else{
            throw new Exception("O evento import {$event->id} não tem decada");
        }
    }
    
    private function _getEventType($event){
        //prioridade para calcular o event type
        if(!empty($event->video)){
            return EventItem::TYPE_VIDEO;
        }elseif(!empty($event->foto)){
            return EventItem::TYPE_IMAGE;
        }elseif(!empty($event->audio)){
            return EventItem::TYPE_AUDIO;
        }else{
            return EventItem::TYPE_TEXT;
        }
    }
    
    private function _getEventMedia($event){
        if(!empty($event->video)){
            return $event->video;
        }elseif(!empty($event->foto)){
            return $this->_getEventMediaId($event);
        }elseif(!empty($event->audio)){
            return $event->audio;
        }else{
            return null;
        }
    }
    
    private function _setEventMedia(EventItem $dbEvent, $event){
        $mediaImport = [
            EventMedia::TYPE_IMAGE => trim($event->foto),
            EventMedia::TYPE_VIDEO => trim($event->video),
            EventMedia::TYPE_AUDIO => trim($event->audio)
        ];
        $position = 1;
        
        foreach($mediaImport as $mediaType => $mediaValue){
            $medias = trim($mediaValue);
            $medias = preg_split( "/(,|;)/", $medias);
            foreach($medias as $mediaFile){ 
                $mediaFile = trim($mediaFile);
                if(empty($mediaFile)){
                    continue;
                }
                
                $eventMedia = new EventMedia();
                $eventMedia->event_item_id = $dbEvent->id;
                $eventMedia->media_type = $mediaType;
                
                if($eventMedia->isImage()){
                    $mediaItem = $this->_getMediaItem($mediaFile);
                
                    if(is_null($mediaItem)){
                        continue;
                    }
                    
                    $eventMedia->media_image_id = $mediaItem->id;
                }else{
                    $eventMedia->media_embed = $mediaFile;
                }
                
                $eventMedia->save();
                $title = $dbEvent->id . " " .$mediaType . " " . $position;
                DB::statement("insert into event_medias_lang (event_media_id,language_id,title)
                    values(?, ?, ?)",
                    array(
                        $eventMedia->id,
                        'pt',
                        $title
                    )
                );
          
                DB::statement("insert into website_objects (object_id, object_type, content_type, slug, status, position)
                    values(?, ?, ?, ?, ?, ?)",
                    array(
                        $eventMedia->id,
                        get_class($eventMedia),
                        "event_media",
                        $this->_generateSlug($title),
                        "published",
                        $position
                    )
                );
              
                $position = $position + 1; 
                
                if($eventMedia->isImage()){
                    $destinationPath = Config::get("path.internal.media");
                    try {
                        $img = Image::make($destinationPath . '/' . $mediaFile);
                    } catch(Exception $e) {
                        throw new Exception("image source not readable - " . $destinationPath . '/' . $mediaFile);
                    }
                    $img->resize(620, null, function ($constraint){
                        $constraint->aspectRatio();
                    });
                    $img->save(Config::get('path.internal.thumbs') . '/' . getFileNameSize($mediaFile, '620'));
                }      
            }
                 
            
        }
    } 
    
    private function _getStartDate($event){
        if(empty($event->ano) || !is_numeric($event->ano)){
            return null;
        }
        
        if(!empty($event->dia) && !empty($event->mes)){
            $mes = explode(",",$event->mes);
            $startMonth = trim($mes[0]); 
            $startMonth = $this->_getMonth($startMonth);
            $dia = explode(",",$event->dia);
            $startDay = $dia[0];
            if(!is_numeric($startDay)){
                return null;
            }
            $startDate = db_date_to_carbon("{$event->ano}-{$startMonth}-{$startDay}");
                  
        }elseif(empty($event->dia) && !empty($event->mes)){
            $mes = explode(",",$event->mes);
            $startMonth = trim($mes[0]);
            $startMonth = $this->_getMonth($startMonth);
            $startDate = db_date_to_carbon("{$event->ano}-{$startMonth}-01");
             
        }else{
            $startDate = db_date_to_carbon("{$event->ano}-01-01");  
        }
        return $startDate;     
    }
    
    private function _getEndDate($event){
        if(!empty($event->dia2) && !empty($event->mes2)){
            $mes = explode(",",$event->mes2);
            $endMonth = trim($mes[0]);
            $endMonth = $this->_getMonth($endMonth);
            $endDate = db_date_to_carbon("{$event->ano}-{$endMonth}-{$event->dia2}");
        }elseif(empty($event->dia2) && !empty($event->mes2)){
            $mes = explode(",",$event->mes2);
            $endMonth = trim($mes[0]);
            $endMonth = $this->_getMonth($endMonth);
            
            $endDate = db_date_to_carbon("{$event->ano}-{$endMonth}-01");
            $endDate->modify("last day of this month");
             
        }elseif(!empty($event->dia2) && empty($event->mes2)){
            $mes = explode(",",$event->mes);
            $endMonth = trim(last($mes));
            $endMonth = $this->_getMonth($endMonth);
            
            $endDate = db_date_to_carbon("{$event->ano}-{$endMonth}-{$event->dia2}");
        }elseif(!empty($event->mes) && strpos($event->mes, ",") !== false){
            $mes = explode(",",$event->mes);
            $endMonth = trim(last($mes));
            $endMonth = $this->_getMonth($endMonth);
            $endDate = db_date_to_carbon("{$event->ano}-{$endMonth}-01");
            $endDate->modify("last day of this month"); 
        }else{
            return null; 
        }
        return $endDate;     
    }

    private function _generateSlug($originSlug){
        $originSlug = urlize($originSlug);
        $slug = $originSlug;
        
        $slugCounter = 1;
        while(WebsiteObject::hasSlug($slug) && $slugCounter <= 100){
            $slug = $originSlug . "-" . $slugCounter;
            $slugCounter++;   
        }
        
        if($slugCounter == 100){
            return false;
        }else{
            return $slug;
        }    
    }
    
    private function _getMonth($monthName){
        $months = [
            "01" => "janeiro",
            "02" => "fevereiro",
            "03" => "março",
            "04" => "abril",
            "05" => "maio",
            "06" => "junho",
            "07" => "julho",
            "08" => "agosto",
            "09" => "setembro",
            "10" => "outubro",
            "11" => "novembro",
            "12" => "dezembro"
        ]; 
        
        if(in_array(strtolower($monthName),$months)){
            $month = array_search(strtolower($monthName), $months);        
        }else{
            throw new Exception("Invalid month -> " . $monthName);
        } 
        
        return $month;  
    }
    
    private function _getEventMediaId($event){
        $images = trim($event->foto);
        
        if(empty($images)){
            return null;
        }
        
        $images = preg_split( "/(,|;)/", trim($event->foto));
        $imageName = trim($images[0]);
        
        $mediaItem = $this->_getMediaItem($imageName);

        if(empty($mediaItem)){
            return null;
        }
        
        $destinationPath = Config::get("path.internal.media");
        $img = Image::make($destinationPath . '/' . $mediaItem->filename);
        $img->resize(620, null, function ($constraint){
            $constraint->aspectRatio();           
        });
        $img->save(Config::get('path.internal.thumbs') . '/' . getFileNameSize($mediaItem->filename, '620'));

        return $mediaItem->id;
            
    }
    
    private function _getMediaItem($fileName){
        if(is_null($this->mediaItems)){
            $this->mediaItems = MediaItem::all();
        }
        
        $imageName = trim($fileName);
        
        if(empty($imageName)){
            return null;
        }
        
        $mediaItem = $this->mediaItems->filter(function(MediaItem $mediaItem) use($imageName){
            return strtolower($mediaItem->original_filename) == strtolower($imageName);   
        })->first();
        
        if(empty($mediaItem)){
            return null;
        }else{
            return $mediaItem;
        }    
    }
    
    private function _getLocationId($locationName){
        $locationName = trim($locationName);
        if(empty($locationName)){
            return null;
        }
        
        if(is_null($this->locations)){
            $this->locations = LocationLanguage::all();
        }

        $location = $this->locations->filter(function(LocationLanguage $location) use($locationName){
            return strtolower($location->title) == strtolower($locationName);   
        })->first();
        
        if(empty($location)){
            return null;
        }
        
        return $location->location_id;
            
    }
    
    private function _getAreaId($areaName){
        $areaName = trim($areaName);
        if(empty($areaName)){
            return null;
        }
        
        if(is_null($this->areas)){
            $this->areas = AreaLanguage::all();
        }

        $area = $this->areas->filter(function(AreaLanguage $area) use($areaName){
            return strtolower($area->title) == strtolower($areaName);   
        })->first();
        
        if(empty($area)){
            return null;
        }
        
        return $area->area_id;
            
    }
    
    private function _setPeopleIds($eventId, $peopleNames){
        $peopleNames = trim($peopleNames);
        if(empty($peopleNames)){
            return ;
        }
       
        $sqlNames = [];
        
        $names = explode(",",$peopleNames);
        foreach($names as $name){
            $sqlName = trim($name);
            if(empty($name)){
                continue;
            }
            $sqlNames[] = DB::connection()->getPdo()->quote($sqlName);
        }

        if (empty($sqlNames)) {
            return;
        }
        
        DB::statement("INSERT INTO event_item_person(event_item_id, person_id) 
            SELECT ?, person_id from people_lang where title in (". implode(",",$sqlNames) .")", array($eventId));
    }
    
    private function _setKeywordsIds($eventId, $dbKeywords){
        $dbKeywords = trim($dbKeywords);
        if(empty($dbKeywords)){
            return ;
        }
       
        $sqlKeywords = [];
        
        $keywords = explode(",",$dbKeywords);
        foreach($keywords as $keyword){
            $sqlKeyword = trim($keyword);
            if(empty($sqlKeyword)){
                continue;
            }
            $sqlKeywords[] = DB::connection()->getPdo()->quote($sqlKeyword);
        }
        
        DB::statement("INSERT INTO event_item_keyword(event_item_id, keyword_id) 
            SELECT ?, keyword_id from keywords_lang where title in (". implode(",",$sqlKeywords) .")", array($eventId));
    }

    private function _setLocationsIds($eventId, $dbLocations){
        $dbLocations = trim($dbLocations);
        if(empty($dbLocations)){
            return ;
        }

        $locationID = $this->_getLocationId($dbLocations);


        DB::statement("INSERT INTO event_item_location(event_item_id, location_id) values(?,?)",array($eventId, $locationID));
    }
   
}
