<?php
/**
 * @link https://craftcms.com/
 * @copyright Copyright (c) Pixel & Tonic, Inc.
 * @license https://craftcms.github.io/license/
 */

namespace craft\shopify\utilities;

use Craft;
use craft\base\Utility;
use craft\shopify\enums\BulkOperationStatus;
use craft\shopify\models\BulkOperation;
use craft\shopify\Plugin;
use craft\web\assets\admintable\AdminTableAsset;

/**
 * Sync class offers the Shopify Sync utilities.
 *
 * @author Pixel & Tonic, Inc. <support@pixelandtonic.com>
 * @since 3.0.0
 */
class Sync extends Utility
{
    /**
     * @inheritdoc
     */
    public static function displayName(): string
    {
        return Craft::t('app', 'Shopify Sync');
    }

    /**
     * @inheritdoc
     */
    public static function id(): string
    {
        return 'shopify-sync';
    }

    /**
     * @inheritdoc
     * @TODO remove this method when support for Craft 4 is dropped
     */
    public static function iconPath(): ?string
    {
        return self::icon(); // TODO: Change the autogenerated stub
    }

    /**
     * @inheritdoc
     */
    public static function icon(): ?string
    {
        return Craft::getAlias('@vendor') . '/craftcms/shopify/src/icon-mask.svg';
    }

    /**
     * @inheritdoc
     */
    public static function contentHtml(): string
    {
        $view = Craft::$app->getView();
        $view->registerAssetBundle(AdminTableAsset::class);

        $bulkOps = Plugin::getInstance()->getBulkOperations()->getAllBulkOperations();

        $canCreateSync = true;

        $formatter = Craft::$app->getFormatter();

        $tableData = $bulkOps->map(function(BulkOperation $bo) use (&$canCreateSync, $formatter) {
            if (in_array($bo->getStatus(), [BulkOperationStatus::Processing, BulkOperationStatus::Created])) {
                $canCreateSync = false;
            }

            return [
                'id' => $bo->id,
                'status' => $bo->statusLabelHtml(),
                'shopifyStatus' => $bo->shopifyStatus,
                'objects' => $bo->objectCount ? $formatter->asInteger($bo->objectCount) : '',
                'dateCreated' => $formatter->asDatetime($bo->dateCreated),
                'dateUpdated' => $formatter->asDatetime($bo->dateUpdated),
                '_showDelete' => $bo->getStatus() !== BulkOperationStatus::Processing,
            ];
        })->all();

        return $view->renderTemplate('shopify/utilities/_sync.twig', [
            'canCreateSync' => $canCreateSync,
            'tableData' => $tableData,
        ]);
    }
}
