<?php

namespace CCDN\Controllers;

use CCDN\Helpers\Api\ApiHandler;
use CCDN\Helpers\Api\Response\Field\IframeUlrField;
use CCDN\Helpers\CCDNUploadPoster;
use CCDN\Helpers\DB\Model;
use CCDN\Helpers\DB\PostMapper;
use CCDN\Helpers\Exception\CCDNException;
use CCDN\Helpers\Facade\Http\Response;
use CCDN\Helpers\Facade\Http\Url;
use CCDN\Helpers\Http\Request;
use CCDN\Helpers\SearchResolver;
use CCDN\Helpers\Settings;
use CCDN\Helpers\SeasonsFranchiseAltUrl;
use CCDN\Helpers\SeasonsFranchiseMetaTitle;
use CCDN\Helpers\SeasonsFranchiseTitle;
use CCDN\Helpers\NotSeasonsFranchiseAltUrl;
use CCDN\Helpers\NotSeasonsFranchiseMetaTitle;
use CCDN\Helpers\NotSeasonsFranchiseTitle;

class UpdatePostController
{
    /**
     * @param Request $request
     *
     * @return string
     * @throws CCDNException
     */
    public function updateFilms(Request $request)
    {
        if (!is_numeric($request->get('chunk'))) {
            throw new CCDNException('Chunk not number');
        }

        $config = Settings::all();
        $postMapper = new PostMapper();
        $searchResolver = new SearchResolver();


        $posts = $postMapper->selectPosts($request->get('chunk'));
        $responses = $searchResolver->multiHandler(new ApiHandler(), $posts);
        foreach ($responses as $postId => $response) {

            $post = $posts[$postId];
            $season = $seasonsNumber = '';
            $episode = $episodesNumber = '';
            $iframeUrl = $response->getIframeUrl()->get();
            $postSeason = $post->getNumberFromField($config->serial_season_field);
            $postEpisode = $post->getNumberFromField($config->serial_episode_field);

            if ($response->getType()->isSeasons()) {

                if ($postEpisode === null || $postSeason === null) {
                    $seasonsNumber = $response->getSeasons()->getLast()->getNumber();
                    $episodesNumber = $response->getSeasons()->getLast()->getEpisodes()->getLast()->getNumber();

                    $season = $seasonsNumber . ' ' . $config->serial_season_field_suffix;
                    $episode = $episodesNumber . ' ' . $config->serial_episode_field_suffix;

                    if ($config->set_season_episode_to_embed !== '0') {
                        $iframeUrl = $response->getSeasons()->getLast()->getEpisodes()->getLast()->getIframeUrl()->get();
                    }
                } elseif ($config->set_season_episode_to_embed !== '0') {
                    $iframeUrl = $response->getSeasons()->get($postSeason)->getEpisodes()->getLast()->getIframeUrl()->get();
                }

                $post->title = SeasonsFranchiseTitle::handler($config, $response, $post);
                $post->alt_name = SeasonsFranchiseAltUrl::handler($config, $response, $post);
                $post->metatitle = SeasonsFranchiseMetaTitle::handler($config, $response, $post);
            } else {
                $post->title = NotSeasonsFranchiseTitle::handler($config, $response, $post);
                $post->alt_name = NotSeasonsFranchiseAltUrl::handler($config, $response, $post);
                $post->metatitle = NotSeasonsFranchiseMetaTitle::handler($config, $response, $post);
            }

            if ($config->button_description === '1' && empty(trim($post->full_story))) {
                $post->full_story = $response->getDescription();
            }

            if ($config->button_short_desc === '1' && empty(trim($post->short_story))) {
                $post->short_story = $response->getDescription();
            }

            $videoVoicesDisabled = (array)$config->getJsonDecode('video_voices_disabled');

            $voiceActingStr = $response->getVoicesActing()->removeFromList($videoVoicesDisabled)->implode();

            $firstVoice = $response->getVoicesActing()
                ->removeFromList($videoVoicesDisabled)
                ->getVoiceActingByPriority($config->getJsonDecode('video_voice_priority'));

            $iframeUrlHandler = new IframeUlrField($iframeUrl);

            $iframeUrl = $iframeUrlHandler->addQueryParam('soundBlock', implode(',', $videoVoicesDisabled))->get();

            $trailerIframeUrl = $response->getTrailers()->getLast()->getIframeUrl()->get();

            $post->setField($config->collaps_franchise_ads_status_field, (int)$response->getAds());
            $post->setField($config->embed_field, $iframeUrl);
            $post->setField($config->kinopoisk_id_field, $response->getKinopoiskId());
            $post->setField($config->imdb_id_field, $response->getImdbId());
            $post->setField($config->world_art_id_field, $response->getWorldArtId());
            $post->setField($config->serial_season_field, $season);
            $post->setField($config->serial_episode_field, $episode);
            $post->setField($config->video_voice_field, $voiceActingStr);
            $post->setField($config->video_first_voice_field, $firstVoice);
            $post->setField($config->video_quality_field, $response->getQuality());
            $post->setField($config->episode_count_field, $response->getSeasons()->getAllEpisodesCount());
            $post->setField($config->ccdn_id_field, $response->getId());
            $post->setField($config->trailer_field, $trailerIframeUrl);
            $post->setField($config->season_franchise_status, $response->getSerialStatus()->toCyrillic());

            if ($config->set_all_date === '1') {
                $post->setField($config->button_name, $response->getName());
                $post->setField($config->button_origin_name, $response->getNameEng());
                $post->setField($config->button_poster, $response->getPoster());
                $post->setField($config->button_year, $response->getYear());
                $post->setField($config->button_country, $response->getCountries()->implode());
                $post->setField($config->button_director, $response->getDirectors()->implode());
                $post->setField($config->button_actors, $response->getActors()->implode());
                $post->setField($config->button_age, $response->getAge());
                $post->setField($config->button_genres, $response->getGenres()->implode());
                $post->setField($config->button_time, $response->getTime());
                $post->setField($config->button_premier, $response->getPremier());
                $post->setField($config->button_premier_rus, $response->getPremierRus());
                $post->setField($config->button_rating_imdb, $response->getImdbRating());
                $post->setField($config->button_rating_kinopoisk, $response->getKinopoiskRating());
                $post->setField($config->button_rating_world_art, $response->getWorldArtRating());
                $post->setField($config->button_trailer, $response->getTrailers()->getLast()->getIframeUrl()->get());

                $post->setField($config->button_slogan, $response->getSlogan());
                $post->setField($config->button_screenwriter, $response->getScreenwriters()->implode());
                $post->setField($config->button_producer, $response->getProducers()->implode());
                $post->setField($config->button_operator, $response->getOperators()->implode());
                $post->setField($config->button_composer, $response->getComposers()->implode());
                $post->setField($config->button_design, $response->getDesigns()->implode());
                $post->setField($config->button_editor, $response->getEditors()->implode());
                $post->setField($config->button_actors_dubbing, $response->getActorsDuplicators()->implode());
                $post->setField($config->button_budget, $response->getBudget());
                $post->setField($config->button_fees_use, $response->getFeesUSA());
                $post->setField($config->button_fees_rus, $response->getFeesRus());
                $post->setField($config->button_fees_world, $response->getFeesWorld());
                $post->setField($config->button_rate_mpaa, $response->getRateMPAA());
                $post->setField($config->button_trivia, $response->getTrivia()->implode("\n\n"));
                $post->setField($config->button_custom_filed_description, $response->getDescription());
                $post->setField($config->button_franchise_type, $response->getType()->getName());
            }

            if ($config->upload_posters === '1' && !empty($config->button_download_poster)) {
                $poster = $post->getField($config->button_download_poster);
                if ($response->getPoster() !== null) {
                    if (!$post->postHasImage() || empty($poster) || !file_exists(ROOT_DIR . "/uploads/posts/" . $poster)) {
                        $result = CCDNUploadPoster::upload($config, $response, $post->id);
                        if (!empty($result['xfvalue'])) {
                            $post->setField($config->button_download_poster, $result['xfvalue']);

                            $poster_url = explode('|', $result['xfvalue'])[0];
                            $post->setField($config->button_download_poster_url, '/uploads/posts/' . $poster_url);
                            $post->setField($config->button_download_poster_url_with_domain, Url::getDomain() . '/uploads/posts/' . $poster_url);
                        }
                    }
                }

                if (!empty($poster)) {
                    $poster_url = explode('|', $poster)[0];
                    $post->setField($config->button_download_poster_url, '/uploads/posts/' . $poster_url);
                    $post->setField($config->button_download_poster_url_with_domain, Url::getDomain() . '/uploads/posts/' . $poster_url);
                }
            }

            if ($config->content_ads_filter === '1' && $response->getAds()) {
                $post->deleteField($config->embed_field);
            }

            $post->updatePost();
        }

        return Response::json([
            'status' => 'Ok'
        ]);
    }

    public function chunksCount()
    {
        $model = new Model();
        $count = $model->select("SELECT COUNT(`id`) as count FROM  {$model->getPrefix()}_post");
        $totalPostCount = (int)$count['count'];
        $chunkLength = Settings::DEFAULT_CHUNK_LENGTH;
        if (Settings::get('upload_posters') === '1') {
            $chunkLength /= 2;
        }
        $chunksCount = ceil($totalPostCount / $chunkLength);

        return Response::json([
            'chunksCount' => $chunksCount,
        ]);

    }
}
