<?php

namespace auctionforge\inc\abs;

use DateTime;
use DateTimeZone;
use auctionforge\inc\ImageUploader;
use auctionforge\inc\InstanceDB;
use auctionforge\inc\model\Lot;
use auctionforge\inc\traits\LoggerInfo;

abstract class InsertLotsAbstract
{
    use LoggerInfo;

    protected function rawDataFilter($rawLots, $postData)
    {
        $new = $rawLots;
        $old = array();
        if (empty($rawLots)) {
            return $rawLots;
        }

        foreach ($postData as $item) {
            if (!empty($rawLots[$item->lotId])) {
                $timestamp = intval($rawLots[$item->lotId]->lastUpdate / 1000);

                if ($item->lastUpdate >= $timestamp) {
                    $old[] = $rawLots[$item->lotId];
                    unset($new[$item->lotId]);
                }
            }
        }
        return array(
            'new' => $new,
            'old' => $old,
        );
    }

    protected function fixResult(Lot $lot, $postId)
    {
        if (!empty($this->instanceLogger()->getErrors())) {
            $lot->updateFields(array(
                'postId' => $postId,
                'syncStart' => 0,
                'syncFinished' => 0,
                'syncErrors' => json_encode($this->instanceLogger()->getErrors()),
            ), array('%d', '%d', '%d', '%s'));
        } elseif (empty($postId)) {
            $lot->updateFields(array(
                'postId' => 0,
                'syncStart' => 0,
                'syncFinished' => 0,
                'syncErrors' => json_encode(['No post created — lot will be retried']),
            ), array('%d', '%d', '%d', '%s'));
        } else {
            $lot->updateFields(array(
                'postId' => $postId,
                'syncStart' => 0,
                'syncFinished' => 1,
                'syncDatetime' => date(Importer::DATE_FORMAT),
                'syncErrors' => ''
            ), array('%d', '%d', '%d', '%s', '%s'));
        }
    }

    /**
     * @param $timestamp
     * @param  bool  $timeZone
     * @return string
     * @throws \Exception
     */
    protected function getDatetimeValue($timestamp, $timeZone = false)
    {
        if (!$timeZone) {
            $timeZone = wp_timezone_string();
        }
        $dt = new DateTime("now", new DateTimeZone($timeZone));
        $dt->setTimestamp($timestamp);
        return $dt->format(Importer::DATE_FORMAT);
    }

    protected function uploadImages($lot, $postId) {
        Lot::updateMetaValue($postId, 'load_images', '0');
        $imageUploader = new ImageUploader($postId, $lot, $this->instanceLogger());

        $this->instanceLogger()->setErrors($imageUploader->instanceLogger()->getErrors());

        $imageUploader->deleteOldAttachment();
        $imageUploader->upload();

        if ($imageUploader->isPostThumbnailSet() && empty($imageUploader->instanceLogger()->getErrors())) {
            Lot::updateMetaValue($postId, 'load_images', '1');
        }
    }

    protected function blockRawLots($rawIds)
    {
        if (!empty($rawIds)) {
            $db = InstanceDB::getInstanceDB();
            $sql = "UPDATE `" . $db->prefix . Importer::TABLE_NAME .
                "` SET `syncstart` = '1', `synctimes` = `synctimes` + 1 WHERE `id` IN (" .
                implode(",", $rawIds) . ")";
            return $db->query($sql);
        }
        return false;
    }

    protected function blockRawRecordsLots($rawIds)
    {
        if (!empty($rawIds)) {
            $db = InstanceDB::getInstanceDB();
            $sql = "UPDATE `" . $db->prefix . Importer::TABLE_NAME .
                "` SET `syncstart` = '1' WHERE `id` IN (" .
                implode(",", $rawIds) . ")";
            return $db->query($sql);
        }
        return false;
    }

    protected function unblockRawRecordsLots($rawIds)
    {
        if (!empty($rawIds)) {
            $db = InstanceDB::getInstanceDB();
            $sql = "UPDATE `" . $db->prefix . Importer::TABLE_NAME . "` SET `syncstart` = '0' WHERE `id` IN (" .
                implode(",", $rawIds) . ")";
            return $db->query($sql);
        }
        return false;
    }

    protected function disableUnUpdatedLots($rawIds)
    {
        if (!empty($rawIds)) {
            $db = InstanceDB::getInstanceDB();
            $sql = "UPDATE `" . $db->prefix . Importer::TABLE_NAME .
                "` SET `postId` = 0, `syncstart` = 0, `syncFinished` = 1 WHERE `id` IN (" .
                implode(",", $rawIds) . ")";
            $db->query($sql);
        }
    }
}