<?php

namespace CCDN\Controllers;

use CCDN\Helpers\Api\ApiHandler;
use CCDN\Helpers\Controller;
use CCDN\Helpers\DB\Model;
use CCDN\Helpers\DB\PostMapper;
use CCDN\Helpers\DB\SettingsSave;
use CCDN\Helpers\Facade\Http\Response;
use CCDN\Helpers\Facade\Http\Url;
use CCDN\Helpers\Http\Request;
use CCDN\Helpers\CCDNFunctions;
use CCDN\Helpers\Settings;
use CCDN\Helpers\XFields;
use GuzzleHttp\Promise;

class CollectionsController extends Controller
{

    protected $viewsFolder = 'collection';
    protected $parent = '';

    public function __construct($parent = 'collections')
    {
        $this->parent = $parent;
    }

    public function main()
    {
        $api = new ApiHandler();
        $ccdnConf = Settings::all();
        global $cat_info;

        $collections = $api->getCollections([
            'limit' => 500
        ]);

        return Response::make($this->render('collection', [
            'ccdnConf' => $ccdnConf,
            'categories' => CCDNFunctions::getSequenceOfCategories($cat_info),
            'collections' => $collections,
            'collectionsBundle' => $ccdnConf->getJsonDecode('collections_bundle'),
            'customFields' => XFields::load(),
        ]));
    }


    public function saveSettings(Request $request)
    {

        $settings = $request->post();

        $json = json_encode(array_filter($request->post('collections_bundle')),
            JSON_UNESCAPED_UNICODE | JSON_HEX_APOS | JSON_HEX_QUOT
        );
        $settings['collections_bundle'] = $json;
        $configSave = new SettingsSave($settings);
        $configSave->collection();

        Response::redirect(Url::to($this->parent));
    }


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

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


    public function update(Request $request)
    {

        $postMapper = new PostMapper();
        $posts = $postMapper->selectPosts($request->get('chunk'));

        $api = new ApiHandler();
        $collections = $api->getCollections([
            'limit' => 500
        ]);

        $kinopoiskIdField = Settings::get('kinopoisk_id_field');
        $collectionField = Settings::get('collection_field');
        $xField = XFields::getField($collectionField);
        $collectionsBundle = json_decode(html_entity_decode(Settings::get('collections_bundle')), true);
        $promises = [];
        $kinopoiskIds = [];
        $postCollections = [];
        foreach ($posts as $post) {
            $kinopoiskIds[] = $post->getField($kinopoiskIdField);
        }

        foreach ($collections as $collection) {
            $id = $collection->getId();
            $promises[$id] = $api->getListAsync([
                'collection_id' => $id,
                'kinopoisk_id' => $kinopoiskIds,
            ]);
        }

        $waitResponses = Promise\settle($promises)->wait();

        $responses = $api->promiseResponseJsonToArray($waitResponses);
        $model = new Model();
        foreach ($responses as $collectionId => $response) {
            if ($response['total'] === 0) {
                continue;
            }

            foreach ($response['results'] as $result) {

                foreach ($posts as $post) {

                    if ($result['kinopoisk_id'] === $post->getField($kinopoiskIdField)) {
                        $collectionName = '';
                        foreach ($collections as $collection) {
                            if ($collection->getId() === $collectionId) {
                                $collectionName = $collection->getName();
                                break;
                            }
                        }
                        $postCollections[$post->id][] = $collectionName;

                        $catIds = explode(',', $post->category);
                        foreach ($collectionsBundle as $catId => $name) {
                            if ($collectionName === $name) {
                                $catIds[] = $catId;

                                $postExtrasCats = $model->select(
                                    "SELECT `news_id` FROM `{$model->getPrefix()}_post_extras_cats` WHERE `news_id`={$post->id} AND `cat_id`={$catId}"
                                );
                                if (empty($postExtrasCats)) {
                                    $model->insert("{$model->getPrefix()}_post_extras_cats", [
                                        'news_id' => $post->id,
                                        'cat_id' => $catId,
                                    ]);
                                }
                                break;
                            }
                        }

                        $posts[$post->id]->category = implode(',', array_filter(array_unique($catIds)));
                    }


                }
            }
        }

        foreach ($postCollections as $postId => $postCollection) {
            $posts[$postId]->setField($collectionField, implode(', ', $postCollection));
            $posts[$postId]->updatePost();
            if ($xField['cross_hyperlinks']) {
                $model->delete("{$model->getPrefix()}_xfsearch", [
                    'news_id' => $posts[$postId]->id,
                ]);

                $xfsearchData = explode(',', $posts[$postId]->getField($collectionField));
                foreach ($xfsearchData as $value) {
                    $model->insert("{$model->getPrefix()}_xfsearch", [
                        'news_id' => $posts[$postId]->id,
                        'tagname' => $collectionField,
                        'tagvalue' => trim($model->getDb()->safesql($value)),
                    ]);
                }
            }
        }

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

    }

}
