<?php
declare(strict_types=1);

namespace Webkul\MobikulGraphQL\Model\Resolver;
if (!defined('DS')) {
    define('DS', DIRECTORY_SEPARATOR);
}

use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Exception\GraphQlInputException;
use Magento\Framework\GraphQl\Exception\GraphQlNoSuchEntityException;
use Magento\Framework\GraphQl\Query\ResolverInterface;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;

/**
 * ProductPageData resolver
 */
class AddReview  extends \Webkul\MobikulGraphQL\Controller\Customer\SaveReview implements \Magento\Framework\GraphQl\Query\ResolverInterface
{

    /**
     * @inheritdoc
     */
    public function resolve(
        Field $field,
        $context,
        ResolveInfo $info,
        array $value = null,
        array $args = null
    ) {
        try {
            $this->wholeData = $args;
            return $this->addReview();
        } catch (\Exception $e) {
            return $e->getMessage();
        }
    }
    public function addReview()
    {
        try {
            $this->verifyRequest();
            $environment = $this->emulate->startEnvironmentEmulation($this->storeId);
            // Checking customer token //////////////////////////////////////////////
            if (!$this->customerId && $this->customerToken != "") {
                $this->returnArray["message"] = __("As customer you are requesting does not exist, so you need to logout.");
                $this->returnArray["otherError"] = "customerNotExist";
                $this->customerId = 0;
            }
            if ($this->customerId == 0) {
                $this->customerId = null;
            }
            $review = $this->review
                ->setEntityPkValue($this->productId)
                ->setStatusId(\Magento\Review\Model\Review::STATUS_PENDING)
                ->setTitle($this->title)
                ->setDetail($this->detail)
                ->setEntityId(1)
                ->setStoreId($this->storeId);
            if ($this->customerId != 0) {
                $review->setCustomerId($this->customerId);
            }
            $review->setNickname($this->nickname)
                ->setReviewId($review->getId())
                ->setStores([$this->storeId])
                ->save();
            foreach ($this->ratings as $ratingId => $optionId) {
                $this->ratingFactory->create()
                    ->setRatingId($ratingId)
                    ->setReviewId($review->getId())
                    ->setCustomerId($this->customerId)
                    ->addOptionVote($optionId, $this->productId);
            }
            $review->aggregate();
            $this->returnArray["message"] = __("Your review has been accepted for moderation.");
            $this->returnArray["success"] = true;
            $this->returnArray["status"] = true;
            $this->emulate->stopEnvironmentEmulation($environment);
            return $this->returnArray;
        } catch (\Magento\Framework\Exception\LocalizedException $e) {
            $this->returnArray["message"] = __($e->getMessage());
            $this->returnArray["success"] = false;
            $this->returnarray["status"] = false;
            $this->helper->printLog($this->returnArray);
            return $this->returnArray;
        } catch (\Exception $e) {
            $this->returnArray["message"] = __($e->getMessage());
            $this->returnArray["success"] = false;
            $this->returnarray["status"] = false;
            $this->helper->printLog($this->returnArray);
            return $this->returnArray;
        }
    }

    /**
     * Verify Request function to verify the request
     *
     * @return void|jSon
     */
    protected function verifyRequest()
    {
        if ($this->getRequest()->getMethod() == "POST" && $this->wholeData) {
            $this->title = $this->wholeData["title"] ?? "";
            $this->detail = $this->wholeData["detail"] ?? "";
            $this->ratings = $this->wholeData["ratings"] ?? "[]";
            $this->ratings = $this->jsonHelper->jsonDecode($this->ratings);
            $this->ratings = $this->createStarRatingData($this->ratings);
            $this->storeId = $this->wholeData["storeId"] ?? 1;
            $this->nickname = $this->wholeData["nickname"] ?? "";
            $this->productId = $this->wholeData["id"] ?? 1;
            $this->customerToken = $this->wholeData["customerToken"] ?? "";
            $this->customerId = $this->helper->getCustomerByToken($this->customerToken);
        } else {
            throw new \Exception(__("Invalid Request"));
        }
    }

    /**
     * CreateStarRatingData function to set the rating data
     *
     * @param array $starVal
     * @return array
     */
    public function createStarRatingData($starVal = []) 
    {
        $arr = [];
        foreach ($starVal as $data) {
            $arr[$data['id']] = $data['starValue'];
        }
        return $arr;
    }
     
}